Golang嵌套模板重定义错误

时间:2014-06-24 03:29:03

标签: templates go nested

我没有足够的功劳来发表对此帖子的评论(Is it possible to have nested templates in Go using the standard library? (Google App Engine)

我尝试按照选定的答案来嵌套Go模板,但我仍然面临模板错误的重新定义。

//contents of base.tmpl
{{define "base"}}
<!DOCTYPE html>
<html>
    <head>
    {{template "header" .}}
    {{template "head" .}}
    </head>
    <body>
    {{template "body" .}}
    </body>
</html>
{{end}}

//contents of header.tmpl
{{define "header"}}
<link rel="stylesheet" type="text/css" href="/css/bootstrap/bootstrap.min.css">
{{end}}

//contents of index.tmpl
{{template "base"}}     
{{define "head"}}{{end}}
{{define "body"}}
<table class="table table-hover">
    <thead>
        <tr>
            <th>#</th>
        <th>Status</th>
        <th>Active Hints</th>
        </tr>
</thead>

<tbody>
{{range .}}
        <tr>
            <td>{{.Id}}</td>
        <td>{{.Satus}}</td>
        <td>{{.ActiveHints}}</td>
        </tr>
{{end}}
</tbody>
</table>
{{end}}

//contents of create.tmpl
{{template "base"}}
{{define "head"}}{{end}}
{{define "body"}}
    <form class="form-horizontal" role="form">
    <div class="form-group">
        <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
        <div class="col-sm-10">
            <input type="email" class="form-control" id="inputEmail3" placeholder="Question" required>
        </div>
    </div>
{{end}}

根据其他SO问题的答案,我分别解析每个模板集并单独执行:

func buildTemplates() {
    tmpl := make(map[string]*template.Template)
    tmpl["index"] = template.Must(template.ParseFiles("templates/admin/base.tmpl", "templates/admin/index.tmpl", "templates/admin/header.tmpl"))
    tmpl["create"] = template.Must(template.ParseFiles("templates/admin/base.tmpl", "templates/admin/create.tmpl", "templates/admin/header.tmpl"))

    for _, v := range tmpl {
        if err := v.ExecuteTemplate(os.Stdout, "base", nil); err != nil {
        log.Fatalf("template execution: %s", err)
        }
    }
}

编译很好,但在执行时:'恐慌:模板:重新定义模板“body”' 我做错了什么?

0 个答案:

没有答案