多个文件的分割模板不提供数据

问题描述 投票:0回答:1

我有1个文件(原始文件)的模板,按预期工作,现在当它变得更大我开始将它分成3 files,只是将原始文件中的数据复制并粘贴到3个文件,我能够看到模板执行成功,但startend模板中缺少数据,只有main模板从structData正确接收数据

例如

startTemple.txt

{{define "start"}}
...

{{end}}


main.txt (here i include both template)

{{template "start"}}
...

{{template "end"}}


endTemplate.txt


{{define "end"}}
...
{{end}}

我使用以下内容

t, err := template.New(mainTemplateName).Funcs(funcMap).ParseFiles(startPath, mainPath, endPath)

err = t.Execute(templFile, structData)
if err != nil {
    logs.Logger.Error(err)
}

我使用前面的确切代码,问题是来自structData的数据在生成后没有出现在startend模板中,只是在main中正确获取structData,我在这里可以缺少什么?

使用硬编码数据成功生成模板(开始主端),但是应该来自structData的数据在生成期间不会添加到startend模板

我应该以某种方式将structData添加到startend吗?

templates go go-templates
1个回答
0
投票

当您使用template调用另一个模板时,默认情况下不设置dot,但您可以将值作为(可选)第二个参数传递给template,如下所示:

{{template "name"  pipeline}}

在你的情况下,你的main.txt模板应该是

{{template "start" .}}
...
{{template "end" .}}

dot的值传递给startend模板。

因为可以通过这种方式设置dot的值,所以还可以以更复杂的方式将模板拆分为多个文件。例如,您可以使用HTML模板以卡片式方式显示用户信息,无论您希望在输出中插入此卡,您都可以调用模板并将其传递给用户,即使是周围的模板也需要其他信息或循环。

有关更多详细信息,请查看text/template文档。这适用于text/templatehtml/template,但只有text/template明确记录,而html/template的文档开头有一个注释告诉你,在哪里可以找到详细的文档。

© www.soinside.com 2019 - 2024. All rights reserved.