Field substitution in nested templates

590 views
Skip to first unread message

Ford Enna

unread,
Apr 28, 2012, 7:19:35 PM4/28/12
to golang-nuts
I trying to figure out if field substitution should work in nested
templates. Here is my sample code.

package main

import (
"html/template"
"os"
"log"
)

func main() {
article := map[string]string{
"Name":"Go Templates",
"Body":"This is a test of nested templates in Go.",
}

pageTemplate, err := template.ParseFiles("page.html", "header.html",
"footer.html")

if err != nil {
log.Fatalf("execution failed: %s", err)
}

pageTemplate.Execute(os.Stdout, article)

if err != nil {
log.Fatalf("execution failed: %s", err)
}
}

page.html
=======
<html>
{{template "header"}}
<div>
{{.Body}}
</div>
{{template "footer"}}
</html>

header.html
=========
{{define "header"}}
<div>
<h1>{{.Name}}</h1>
</div>
{{end}}

footer.html
========
{{define "footer"}}
<div>
Copyright 2012
</div>
{{end}}


The result of this code is.

<html>

<div>
<h1></h1>
</div>

<div>
This is a test of nested templates in Go.
</div>

<div>
Copyright 2012
</div>

</html>

As can be seen field substitution failed in the header between <h1></
h1>

David Symonds

unread,
Apr 28, 2012, 9:30:18 PM4/28/12
to Ford Enna, golang-nuts
You need to declare the data to use for the template invocation. You
probably want
{{template "header" .}}


Dave.

rog...@lommers.org

unread,
May 28, 2015, 2:57:18 PM5/28/15
to golan...@googlegroups.com, ford...@gmail.com
Thanks; this fixed my problem!

brydav...@gmail.com

unread,
Feb 16, 2017, 10:58:19 AM2/16/17
to golang-nuts, ford...@gmail.com, rog...@lommers.org
Still works as of Go 1.7
Reply all
Reply to author
Forward
0 new messages