英文:
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}}
{{.Page.Test}}
{{end}}
英文:
I need help.
I need to use "html/template"'s marking ({{.Title}}, example) in sub-files("article.html", example in my text):
// ...
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)
}
Code in core.tmpl:
{{template "article"}}
Code in article.tmpl:
{{define "article"}}
{{.Title}}<br><br>
{{.Page.Test}}
{{end}}
答案1
得分: 2
在你的core.tmpl文件中,你需要使用以下代码:
{{template "article" .}}
如果你不在末尾指定.,模板将使用nil数据执行。指定.将把.的值传递给被调用的模板。
引用自text/template包的文档中的Actions部分:
{{template "name"}}
使用`nil`数据执行指定名称的模板。
{{template "name" pipeline}}
使用管道的值将`.`设置为指定名称的模板。
英文:
In your core.tmpl you have to use
{{template "article" .}}
If you don't specify the . at the end, the template will be executed with nil data. Specifying the . will pass the value of . to the invoked template.
Quoting from the text/template package documentation, Actions section:
{{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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论