Ari Seyhun
Ari Seyhun

Reputation: 12531

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?

Upvotes: 0

Views: 1121

Answers (2)

djd
djd

Reputation: 5178

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.

Upvotes: 1

zzn
zzn

Reputation: 2465

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.

Upvotes: 1

Related Questions