Search code examples
gogo-html-template

In html/templates is there any way to have a constant header/footer across all pages?


Reading the docs wasn't particularly helpful and I want to know if the structure

{{header}}

   {{content that always changes}}

{{footer}}

is achievable with golang.


Solution

  • Using text/template:

    1. Code to render it to Stdout

      t := template.Must(template.ParseFiles("main.tmpl", "head.tmpl", "foot.tmpl"))
      t.Execute(os.Stdout, nil)
      
    2. main.tmpl:

      {{template "header" .}}
      <p>main content</p>
      {{template "footer" .}}
      
    3. foot.tmpl:

      {{define "footer"}}
      <footer>This is the foot</footer>
      {{end}}
      
    4. head.tmpl:

      {{define "header"}}
      <header>This is the head</header>
      {{end}}
      

    This will result in:

    <header>This is the head</header>
    <p>main content</p>
    <footer>This is the foot</footer>
    

    Using html/template will be extremely similar.