英文:
Variable in template's included template
问题
我正在尝试将值放入一个名为"header"的模板中,比如标题和导航链接,但无法从被包含的模板中访问我从主模板发送的变量。
渲染模板的代码如下:
...
templateName := "index"
args := map[string]string{
"Title": "主页",
"Body": "这是内容",
}
PageTemplates.ExecuteTemplate(w, templateName+".html", args)
...
index.html模板如下:
{{template "header"}} <!-- 包含"header.html"模板 -->
{{.Body}} <!-- 正常工作的变量 -->
{{template "footer"}} <!-- 不重要 -->
header.html模板如下:
{{define "header"}}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{.Title}}</title> <!-- 变量为空 :(
</head>
<body>
{{end}}
显然,这种方式行不通。
也许有一种方法可以解析/获取模板,并将我的变量放入其中,而不需要将整个头文件放入代码中?然后我可以将该模板作为变量发送到我的主模板。但这似乎不是最好的方法。
英文:
I am trying to put values into a "header" template, like the title and navigation links but can't access the variables that I sent to the main template from the included one.
Rendering the template:
...
templateName := "index"
args := map[string]string{
"Title": "Main Page",
"Body": "This is the content",
}
PageTemplates.ExecuteTemplate(w, templateName+".html", args)
...
index.html template:
{{template "header"}} <-- Including the "header.html" template
{{.Body}} <-- Variable that works
{{template "footer"}} <-- Does not matter!
header.html template:
{{define "header"}}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{.Title}}</title> <-- Variable empty :(
</head>
<body>
{{end}}
Apparently, it won't work that way.
Maybe there's a way I could parse/get the template and put my variables into it without putting the whole header file into code? Then I could just send that template as a variable to my main template. But that does not seem like it would be the best way to do it.
答案1
得分: 4
你可以在调用模板时将上下文传递给它。在你的例子中,将{{template "header"}}
更改为{{template "header" .}}
应该就足够了。
官方文档中相关的部分如下:
{{template "name"}}
使用空数据执行指定名称的模板。{{template "name" pipeline}}
使用管道的值将dot设置为指定名称的模板的值。
PS:这与问题无关,但你还应该删除{{define "header"}}
和<!DOCTYPE html>
之间的换行符,这样doctype才会真正成为模板中的第一件事。
英文:
You can pass the context to the template when you call it. In your example, changing {{template "header"}}
to {{template "header" .}}
should be sufficient.
The relevant parts from the official docs:
> {{template "name"}}<br>
> The template with the specified name is executed with nil data.
>
> {{template "name" pipeline}}<br>
> The template with the specified name is executed with dot set to the value of the pipeline.
PS: It is not relevant to the question, but you should also remove the newline between {{define "header"}}
and <!DOCTYPE html>
, so that the doctype is really the first thing in your template.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论