一个布局模板和三个子模板。
layout.html
<html>
<body>
{{template "tags"}}
{{template "content"}}
{{template "comment"}}
</body>
</html>tags.html
{{define "tags"}}
<div>
{{.Name}}
<div>
{{end}}content.html
{{define "content"}}
<div>
<p>{{.Title}}</p>
<p>{{.Content}}</p>
</div>
{{end}}comment.html
{{define "tags"}}
<div>
{{.Note}}
</div>
{{end}}gocode
type Tags struct {
Id int
Name string
}
type Content struct {
Id int
Title string
Content string
}
type Comment struct {
Id int
Note string
}
func main() {
tags := &Tags{"Id":1, "Name":"golang"}
Content := &Content{"Id":9, "Title":"Hello", "Content":"World!"}
Comment := &Comment{"Id":2, "Note":"Good Day!"}
}我对如何渲染每个子模板并将结果组合到布局输出中感到困惑。
谢谢。
发布于 2013-10-24 01:08:09
一如既往,the doc是一个很好的起点。
I wrote a working example on the playground
简单解释一下:
&Tags{"Id":1}
{{template <name> <arg>}}指令中的要求将对象分派到每个子模板。map[string]interface{}文件,ParseFiles也可以)以及整个代码:
package main
import "fmt"
import "html/template"
import "os"
var page = `<html>
<body>
{{template "tags" .Tags}}
{{template "content" .Content}}
{{template "comment" .Comment}}
</body>
</html>`
var tags = `{{define "tags"}}
<div>
{{.Name}}
<div>
{{end}}`
var content = `{{define "content"}}
<div>
<p>{{.Title}}</p>
<p>{{.Content}}</p>
</div>
{{end}}`
var comment = `{{define "comment"}}
<div>
{{.Note}}
</div>
{{end}}`
type Tags struct {
Id int
Name string
}
type Content struct {
Id int
Title string
Content string
}
type Comment struct {
Id int
Note string
}
type Page struct {
Tags *Tags
Content *Content
Comment *Comment
}
func main() {
pagedata := &Page{Tags:&Tags{Id:1, Name:"golang"},
Content: &Content{Id:9, Title:"Hello", Content:"World!"},
Comment: &Comment{Id:2, Note:"Good Day!"}}
tmpl := template.New("page")
var err error
if tmpl, err = tmpl.Parse(page); err != nil {
fmt.Println(err)
}
if tmpl, err = tmpl.Parse(tags); err != nil {
fmt.Println(err)
}
if tmpl, err = tmpl.Parse(comment); err != nil {
fmt.Println(err)
}
if tmpl, err = tmpl.Parse(content); err != nil {
fmt.Println(err)
}
tmpl.Execute(os.Stdout, pagedata)
}https://stackoverflow.com/questions/19546896
复制相似问题