4

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.

m0meni
  • 16,006
  • 16
  • 82
  • 141
  • 2
    In case you missed it, read the [`text/template`](https://golang.org/pkg/text/template/) documentation. –  Jun 11 '15 at 19:17
  • @TimCooper I did miss that :O – m0meni Jun 11 '15 at 19:18
  • So would it be done using named templates? '{{template "name"}} The template with the specified name is executed with nil data.' – m0meni Jun 11 '15 at 19:22
  • 1
    That will work if you do not want to pass any data to the template. Otherwise, you'd probably do something like `{{ template "header" . }}`. –  Jun 11 '15 at 19:25
  • @TimCooper Could the name of the template be dynamic? For example, could the page URL be passed in? Something like this? {{template .Page .}} – m0meni Jun 11 '15 at 19:44
  • 1
    That doesn't appear to be possible https://play.golang.org/p/C83SBwaZ_O –  Jun 11 '15 at 19:48
  • @TimCooper so is there no way to have a constant header footer and dynamically changing content in the middle? – m0meni Jun 11 '15 at 19:53
  • 1
    You could always write out your header, content, and footer separately. For example: `headerTPL.Execute(out, data); contentTPL.Execute(out, data); footerTPL.Execute(out, data)`. –  Jun 11 '15 at 20:04

1 Answers1

2

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.

Ezra
  • 7,552
  • 1
  • 24
  • 28
  • 2
    Note that you can put multiple templates in the same source file with multiple `define ... end` blocks. – Ezra Jun 11 '15 at 19:36
  • I'm not 100%, but I think you'd have to use `if ... else` which kind of muddies the waters. My gut feeling is that this kind of logic should be in the code to render the templates, and not the templates themselves. So you'd maybe have `{{ .RenderedPageContent }}` instead of `{{ template .Page . }}`? – Ezra Jun 11 '15 at 20:32