英文:
Parse Custom Variables Through Templates in Golang
问题
在模板文件中设置一个变量{{$title := "Login"}}
,然后通过{{template "header" .}}
将其传递到另一个包含的文件中,这种做法是可行的。
以下是你尝试的示例:
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}}
你想知道如何将我创建的自定义$title
变量传递到我的header模板中。
英文:
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?
答案1
得分: 1
不,不可能将变量解析到另一个文件中。
根据这个链接的说明:
变量的作用域延伸到声明它的控制结构("if"、"with"或"range")的"end"操作,或者如果没有这样的控制结构,则延伸到模板的末尾。模板调用不会从其调用点继承变量。
英文:
no, it's impossible parse variable through to another file.
according to this:
> A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared, or to the end of the template if there is no such control structure. A template invocation does not inherit variables from the point of its invocation.
答案2
得分: 1
如@zzn所说,不可能从一个模板中引用另一个模板中的变量。
实现你想要的方式之一是定义一个模板,它将从一个模板传递到另一个模板。
header.html
{{define "header"}}
<title>{{template "title"}}</title>
{{end}}
login.html
{{define "title"}}Login{{end}}
{{define "login"}}
<html>
<head>
{{template "header" .}}
</head>
<body>
Login Body!
</body>
</html>
{{end}}
当你调用"header"模板时,你也可以将标题作为管道传递({{template header $title}}
或者{{template header "index"}}
),但这将阻止你向该模板传递其他内容。
英文:
As @zzn said, it's not possible to refer to a variable in one template from a different one.
One way to achieve what you want is to define a template – that will pass through from one template to another.
header.html
{{define "header"}}
<title>{{template "title"}}</title>
{{end}}
login.html
{{define "title"}}Login{{end}}
{{define "login"}}
<html>
<head>
{{template "header" .}}
</head>
<body>
Login Body!
</body>
</html>
{{end}}
You could also pass through the title as the pipeline when you invoke the "header" template ({{template header $title}}
or even {{template header "index"}}
), but that will prevent you passing in anything else to that template.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论