包含模板的模板中的变量 [英] Variable in template's included template

查看:164
本文介绍了包含模板的模板中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将值放入标题模板中,如标题和导航链接,但无法访问我从包含模板发送到主模板的变量。



呈现模板:

  ... 
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。}} 应该足够了。 > 官方文档中的相关部分:


{{templatename}}

具有指定名称的模板以零数据执行。



{{templatenamepipeline}}

Th具有指定名称的e模板将使用设置为管道值的点执行。


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:

{{template "name"}}
The template with the specified name is executed with nil data.

{{template "name" pipeline}}
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.

这篇关于包含模板的模板中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆