Templates 如何使用结构或变量值字段作为模板名称?
我们可以通过Templates 如何使用结构或变量值字段作为模板名称?,templates,go,go-templates,Templates,Go,Go Templates,我们可以通过{define“home”}定义模板名称,然后通过{template“home”}将其加载到其他(父)模板中 如何通过变量值{{template.TemplateName}}加载模板。或者这是不可能的?不幸的是,你不能 {{template}}操作的语法: {{template "name"}} The template with the specified name is executed with nil data. {{template "name" pipeline
{define“home”}
定义模板名称,然后通过{template“home”}
将其加载到其他(父)模板中
如何通过变量值
{{template.TemplateName}}
加载模板。或者这是不可能的?不幸的是,你不能
{{template}}
操作的语法:
{{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.
要包含的模板名称是一个常量字符串,它不是一个管道,在执行过程中可能会根据参数发生变化
如果允许的语法为:
{{template pipeline}}
然后您可以使用类似于{{template.templaname}}
的东西,但是由于语法只允许常量字符串,所以您不能
Rob推理为什么不允许动态模板调用():
我们希望模板语言能够进行静态分析,以便模板调用的上下文清晰、可检查且可锁定。如果调用点是完全动态的,则无法完成此操作。类似地,如果模板可以属于多个集合,则其上下文在集合之间可能会有所不同,这将要求同时分析所有集合。由于如果您愿意,这两个约束都很容易解决,代价是在更高级别的包中丢失这些静态检查,因此控制基本模板实现中的情况似乎是明智的。如果约束是明确的,则更高级别的包(例如假设的纯HTML包装器)可以更容易地保证没有解决方法
备选方案1:首先执行可包含模板
您可以做的是首先执行要包含的模板,然后将结果插入要包含它的位置。插入时,可以使用特殊类型不转义内部模板的结果,例如在HTML模板的情况下
请参见此示例:
func main() {
t := template.Must(template.New("t").Parse(t))
template.Must(t.New("t1").Parse(t1))
params := struct {
Name string
Value interface{}
}{"t1", nil}
b := bytes.Buffer{}
t.ExecuteTemplate(&b, params.Name, nil)
params.Value = template.HTML(b.String())
t.Execute(os.Stdout, params)
}
const t = `<html><body>
Now I will include template with name: {{.Name}}
{{.Value}}
</body>/html>`
const t1 = `I'm template <b>t1</b>.`
t1
将被插入并转义,如下所示:
<html><body>
Now I will include template with name: t1
I'm template <b>t1</b>.
</body>/html>
<html><body>
Title, headers etc.
{{template .Page}}
Footers
</body></html>
{{template "header" .}}
Page content comes here.
{{template "footer" .}}
您可以将其重组为以下内容:
<html><body>
Now I will include template with name: t1
I'm template <b>t1</b>.
</body>/html>
<html><body>
Title, headers etc.
{{template .Page}}
Footers
</body></html>
{{template "header" .}}
Page content comes here.
{{template "footer" .}}
标题
模板:
<html><body>
Title, headers, etc.
Footers
</body></html
您的页面模板将包括页眉
和页脚
,如下所示:
<html><body>
Now I will include template with name: t1
I'm template <b>t1</b>.
</body>/html>
<html><body>
Title, headers etc.
{{template .Page}}
Footers
</body></html>
{{template "header" .}}
Page content comes here.
{{template "footer" .}}
备选方案#3:使用{{if}
操作和预定义名称
如果您知道之前的模板名称,并且它不是一个详尽的列表,那么可以使用{{If}}
模板操作来包含所需的模板。例如:
{{if eq .Name "page1"}}
{{template "page1" .}}
{{else if eq .Name "page2"}}
{{template "page2" .}}
...
{{end}}
备选方案4:修改静态模板文本
这里的想法是,您可以手动修改外部模板的静态文本,并插入要包含的内部模板的名称
这种方法的缺点是,在插入内部模板的名称后,您必须重新解析模板,因此我不建议这样做。谢谢,@icza。真的,我现在很恐慌:)。我认为简单的方法是存在的。您的变体非常好,但在我的情况下,我更喜欢这样使用
{{{if.IsArticle}{{template”article.}}{{else}{{template”page.}{{{end}}
。其中,IsArticle
bool标志基于用户请求(URL)。@user4611478如果您之前知道模板名称,这也是一个非常好的选择,而且它不是一个累人的列表。如果你不介意的话,我会把它包括在答案中。谢谢你,两年后我问自己如何处理这种情况,似乎使用一堆{{{if}}
真的是一种方法。。。