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?

Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109

2 Answers2

1

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.

zzn
  • 2,376
  • 16
  • 30
  • Is there any alternative way to do what I'm trying? – Ari Seyhun May 10 '17 at 05:33
  • define `title` variable in golang, pass it to `template.Execute` function. – zzn May 10 '17 at 05:38
  • 1
    The only other way I can think of, is to include the `header.tmpl` with `{{template "header" "Title Here"}}` then in `header.tmpl` I could use `{{.}}` to access that title. Only issue is, it would be nice if I can add a description or some other data (only through the template) – Ari Seyhun May 10 '17 at 05:44
  • Anyone else looking for an answer... check out http://technosophos.com/2013/11/23/using-custom-template-functions-in-go.html - The best method for me was to make two seperate functions: `get` and `set` for defining globally accessible variables. – Ari Seyhun May 10 '17 at 06:35
1

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.

djd
  • 4,988
  • 2
  • 25
  • 35