2017-05-10 03:26
浏览 140


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:


{{define "header"}}


{{define "login"}}
        {{$title := "Login"}}
        {{template "header" .}}
        Login Body!

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongren9739 2017-05-10 09:02

    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.

    解决 无用
    打赏 举报
  • dongya2030 2017-05-10 05:24

    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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题