templates - tmpl.执行并分文件golang

标签 templates go

我需要帮助。 我需要在子文件("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}}

最佳答案

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

关于templates - tmpl.执行并分文件golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28874194/

相关文章:

c++ - 使用不同的enable_if条件选择方法

go - 'go'工具安装可执行文件后如何访问资源文件?

golang 接受已经打开的 fd

go - 如何将数据添加到在 Go 中作为参数的接口(interface)?

c++ - 推断模板参数对象成员的类型

c++ - 模板的模板成员的消歧模板关键字 : when exactly?

templates - 如何在 CouchDB 中使用 html 模板

c++ - golang select 语句是如何实现的?

go - 检查纬度/经度点是否在区域内

c++ - 你能在 C++ 元编程中的 "hop"之间 "linked classes"吗?