0
在golang,我有三個文件時:的index.html,nav.html和main.goGolang訪問模板變量從包含的模板
nav.html包含以下內容:
{{ define "nav" }}
<nav class="nav-container">
<h1>{{ .path }}</h1>
</nav>
{{ end }}
的index.html包含以下內容:
{{ define "index" }}
{{ template "nav" }} <!-- Includes the nav.html file -->
<h1>Welcome to my website. You are visiting {{ .path }}.</h1>
{{ end }}
我正在使用Golang的template包以及Martini這在這種情況下並不太重要。
我main.go文件包含:
package main
import (
"net/http"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
)
func main() {
m := martiniSetup()
m.Get("/", func(res http.ResponseWriter, req *http.Request, ren render.Render, params martini.Params) {
parse := make(map[string]interface{})
parse["path"] = req.URL.Path
ren.HTML(http.StatusOK, "index", parse)
})
m.Run()
}
我的問題:
的.path
變量被解析成index
模板只能由index
模板本身accessable。
我在index.html
的內部使用{{ template "nav" }}
包含nav
模板。問題是,nav.html
無法訪問.path變量。它只能由索引模板訪問。
有什麼辦法可以使.path
變量可以訪問所有包含的模板文件,在我的例子中是index.html
和nav.html
?
非常感謝!這工作! :) – Acidic