Search code examples
gogo-templates

Variable in template's included template


I am trying to put values into a "header" template, like the title and navigation links but can't access the variables that I sent to the main template from the included one.

Rendering the template:

    ...
    templateName := "index"
    args := map[string]string{
            "Title":       "Main Page",
            "Body":        "This is the content",
    }
    PageTemplates.ExecuteTemplate(w, templateName+".html", args)
    ...

index.html template:

   {{template "header"}} <-- Including the "header.html" template
   {{.Body}}             <-- Variable that works
   {{template "footer"}} <-- Does not matter!

header.html template:

   {{define "header"}}
   <!DOCTYPE html>
   <html lang="en">
   <head>
            <title>{{.Title}}</title> <-- Variable empty :(
   </head>
   <body>
   {{end}}

Apparently, it won't work that way.

Maybe there's a way I could parse/get the template and put my variables into it without putting the whole header file into code? Then I could just send that template as a variable to my main template. But that does not seem like it would be the best way to do it.


Solution

  • You can pass the context to the template when you call it. In your example, changing {{template "header"}} to {{template "header" .}} should be sufficient.

    The relevant parts from the official docs:

    {{template "name"}}
    The template with the specified name is executed with nil data.

    {{template "name" pipeline}}
    The template with the specified name is executed with dot set to the value of the pipeline.

    PS: It is not relevant to the question, but you should also remove the newline between {{define "header"}} and <!DOCTYPE html>, so that the doctype is really the first thing in your template.