0

Is it possible for me to set a variable in a template file {{$title := "Login"}} then parse it through to another file included using {{template "header" .}}?

An example of what I'm attempting:

header.tmpl

{{define "header"}}
<title>{{.title}}</title>
{{end}}

login.tmpl

{{define "login"}}
<html>
    <head>
        {{$title := "Login"}}
        {{template "header" .}}
    </head>
    <body>
        Login Body!
    </body>
</html>
{{end}}

How can I parse this custom $title variable I made through to my header template?

4

2 回答 2

1

正如@zzn 所说,不可能从一个模板中引用另一个模板中的变量。

实现您想要的一种方法是定义一个模板——它将从一个模板传递到另一个模板。

header.html {{define "header"}} <title>{{template "title"}}</title> {{end}}

登录.html {{define "title"}}Login{{end}} {{define "login"}} <html> <head> {{template "header" .}} </head> <body> Login Body! </body> </html> {{end}}

当您调用“标题”模板({{template header $title}}甚至{{template header "index"}})时,您也可以将标题作为管道传递,但这会阻止您将任何其他内容传递给该模板。

于 2017-05-10T09:02:21.637 回答
1

不,不可能将变量解析到另一个文件。

据此:_

变量的范围扩展到声明它的控制结构(“if”、“with”或“range”)的“结束”操作,如果没有这样的控制结构,则扩展到模板的末尾。模板调用不会从其调用点继承变量。

于 2017-05-10T05:24:47.373 回答