gogo-templatestemplate-variables

Parse Custom Variables Through Templates in Golang


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?


Solution

  • 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.