英文:
Golang Accessing Template Variables From Included Templates
问题
在golang中,我正在使用三个文件:index.html、nav.html和main.go。
nav.html包含以下内容:
{{ define "nav" }}
<nav class="nav-container">
<h1>{{ .path }}</h1>
</nav>
{{ end }}
index.html包含以下内容:
{{ define "index" }}
{{ template "nav" }} <!-- 包含nav.html文件 -->
<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()
}
我的问题是:被解析到index模板中的.path
变量只能被index模板本身访问。
我在index.html中使用{{ template "nav" }}
包含了nav模板。问题是,nav.html无法访问.path变量。它只能被index模板访问。
在我的情况下,有没有办法使.path变量对所有包含的模板文件都可访问,包括index.html和nav.html?
英文:
In golang, I am working with three files: index.html, nav.html and main.go
nav.html contains the following:
{{ define "nav" }}
<nav class="nav-container">
<h1>{{ .path }}</h1>
</nav>
{{ end }}
index.html contains the following:
{{ define "index" }}
{{ template "nav" }} <!-- Includes the nav.html file -->
<h1>Welcome to my website. You are visiting {{ .path }}.</h1>
{{ end }}
I am using Golang's template package along with Martini which is not too important in this case.
My main.go file contains:
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()
}
My problem:
The .path
variable being parsed into the index
template is only accessable by the index
template itself.
I include the nav
template using {{ template "nav" }}
inside index.html
. The issue is, nav.html
cannot access the .path variable. It is only accessable by the index template.
Is there any way to make the .path
variable accessable to all included template files, in my case index.html
and nav.html
?
答案1
得分: 3
你可以像这样将数据作为参数传递给嵌套模板:{{ template "nav" . }}
现在,点号(dot)将在define "nav"
块内可访问。
英文:
You can pass the data to the nested template as an argument like this: {{ template "nav" . }}
Now the dot will be accessible within the define "nav"
block.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论