tmpl.Execute和子文件golang

时间:2015-03-05 09:25:11

标签: templates go

我需要帮助。 我需要在子文件("html/template"中使用{{.Title}}标记("article.html",示例),例如在我的文字中:

// ...
type Page struct {
    Test string
}

type News struct {
    Page
    Title string
}

func main() {
    t, _ := template.ParseFiles(filepath+"core.tmpl", filepath+"article.tmpl")
    p := &News{
        Title: "TITLE",
        Page: Page{
            Test: "TITLE",
        },
    }
    t.Execute(wr, p)
}

core.tmpl中的代码:

{{template "article"}}

article.tmpl中的代码:

{{define "article"}}
{{.Title}}<br><br>
{{.Page.Test}}
{{end}}

1 个答案:

答案 0 :(得分:2)

core.tmpl中你必须使用

{{template "article" .}}

如果您未在结尾指定.,则会使用nil数据执行模板。指定.会将.的值传递给调用的模板。

引用text/template包文档Actions部分:

{{template "name"}}
    The template with the specified name is executed with nil data.

{{template "name" pipeline}}
    The template with the specified name is executed with dot set
    to the value of the pipeline.
相关问题