tmpl.Execute 和子文件 golang

tmpl.Execute and sub-file golang

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

// ...
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}}

在你的 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.