2

I have a layout template (base.tmpl) that I would like to use several times in login page (login.tmpl), main content page (main.tmpl), and so on.

base.tmpl file:

{{define "base"}}
<html>
    <head>
        {{block "header" .}}
            <title>Untitled</title>
        {{end}}
    </head>
    <body>
        <div id="main-content">
            {{block "content" .}} {{end}}
        </div>
        {{block "footer" .}} {{ end}}
    </body>
</html>
{{end}}

The pages have a first directive to use the base layout and they can define header, content and footer blocks.

login.tmpl file:

{{template "base"}}

{{define "header"}}
    <title>Login</title>
    <link rel="stylesheet" href="styles.css">
{{end}}

{{define "content" }}
    <input type="username">
    <input type="submit" value="Login">
{{end}}

main.tmpl file:

{{template "base"}}

{{define "header"}}
    <title>Main content</title>
{{end}}

{{define "content" }}
    <h1>Welcome</h1>
{{end}}

{{define "footer" }}
    <script>console.log("ok");</script>
{{end}}

Loading and render template functions:

// 'templates' is a global variable
func LoadTemplates(files []string) {
    templates = template.Must(template.New("myTemplates").ParseFiles(files...))
}

func Render(w http.ResponseWriter, tmpl string, data interface{}) {
    templates.ExecuteTemplate(w, tmpl, data)
}

Using my code to render login page:

// the following line is a simplification, actually I load all files together once.
LoadTemplates(string[]{"base.tmpl", "login.tmpl", "main.tmpl"})
Render(w, "login.tmpl", struct{}{})

Using my code to render main content page:

// the following line is a simplification, actually I load all files together once.
LoadTemplates(string[]{"base.tmpl", "login.tmpl", "main.tmpl"})
Render(w, "login.tmpl", struct{}{})

The problem is that the content block is overwritten because it is twice. So, if I render login or main page, I see the same.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Amparo
  • 784
  • 1
  • 4
  • 21

1 Answers1

0

The solution is to have multiple template "sets" as answered here:

https://stackoverflow.com/a/11468132/2908337