问题描述
我正在尝试将值放入标题模板中,如标题和导航链接,但无法访问我从包含模板发送到主模板的变量。
呈现模板:
...
templateName:=index
args:= map [string] string {
Title:主页,
Body:这是内容,
}
PageTemplates.ExecuteTemplate (w,templateName +。html,args)
...
index.html模板:
{{templateheader}}< - 包含header.html模板
{{.Body}}< - 变量
{{templatefooter}}< - 无关紧要!
header.html模板:
{{defineheader}}
<!DOCTYPE html>
< html lang =en>
< head>
< title> {{。标题}}< / title> < - 变量empty:
< / head>
< body>
{{end}}
显然,它不会那样工作。
也许有一种方法可以解析/获取模板和把我的变量放到它里面,而不是把整个头文件放到代码中?然后我可以把这个模板作为一个变量发送到我的主模板中,但是这看起来并不是最好的方式。 b $ b
当你调用它时,你可以将上下文传递给模板,在你的例子中,改变 {{template
} to {{templateheader。}} 应该足够了。 > 中的相关部分:
PS:与问题无关,但你也应该删除 {{defineheader}} 和<!DOCTYPE html> 之间的换行符, ,所以doctype实际上是您模板中的第一件事。
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.
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:
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.
这篇关于包含模板的模板中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!