Skip to content

Commit 21c2f74

Browse files
committed
Add parent example
1 parent 079913c commit 21c2f74

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package template_test
2+
3+
import (
4+
"log"
5+
"os"
6+
"text/template"
7+
)
8+
9+
func ExampleTemplate_parent() {
10+
const base_html = `<!DOCTYPE html>
11+
<html>
12+
<head>
13+
<title>{{block "title" .}}My website{{end}}</title>
14+
</head>
15+
<body>
16+
<main>
17+
{{- block "content" .}}{{end -}}
18+
</main>
19+
<footer>
20+
{{- block "footer" .}}
21+
<p>Thanks for visiting!</p>
22+
{{- end}}
23+
</footer>
24+
</body>
25+
</html>
26+
27+
`
28+
base := template.Must(template.New("base.html").Parse(base_html))
29+
30+
const index_html = `{{define "content"}}<h1>Welcome!</h1>{{end}}`
31+
index := template.Must(template.Must(base.Clone()).New("index.html").Parse(index_html))
32+
33+
{
34+
err := index.ExecuteTemplate(os.Stdout, "base.html", nil)
35+
if err != nil {
36+
log.Println("executing template:", err)
37+
}
38+
}
39+
40+
const about_html = `{{define "title"}}{{template parent .}} - About{{end}}
41+
{{define "content"}}<h1>About us</h1>{{end}}`
42+
about := template.Must(template.Must(base.Clone()).New("about.html").Parse(about_html))
43+
44+
{
45+
err := about.ExecuteTemplate(os.Stdout, "base.html", nil)
46+
if err != nil {
47+
log.Println("executing template:", err)
48+
}
49+
}
50+
51+
// Output:
52+
// <!DOCTYPE html>
53+
// <html>
54+
// <head>
55+
// <title>My website</title>
56+
// </head>
57+
// <body>
58+
// <main><h1>Welcome!</h1></main>
59+
// <footer>
60+
// <p>Thanks for visiting!</p>
61+
// </footer>
62+
// </body>
63+
// </html>
64+
//
65+
// <!DOCTYPE html>
66+
// <html>
67+
// <head>
68+
// <title>My website - About</title>
69+
// </head>
70+
// <body>
71+
// <main><h1>About us</h1></main>
72+
// <footer>
73+
// <p>Thanks for visiting!</p>
74+
// </footer>
75+
// </body>
76+
// </html>
77+
78+
}

0 commit comments

Comments
 (0)