duanshaiduhao2471 2018-09-01 20:47
浏览 20
已采纳

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

I've template with 1 file (original file)which works as expected, now when it comes bigger I've started to divide it to 3 files and just copy and paste the data from the original file to 3 files and I was able to see that the template was executed successfully but the data is missing in the start and the end template ,just the main template receive the data properly from structData

for example

startTemple.txt

{{define "start"}}
...

{{end}}


main.txt (here i include both template)

{{template "start"}}
...

{{template "end"}}


endTemplate.txt


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

I use the following

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

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

I use the exact code as before and the issue is that the data from structData is not appear in start and end template after generation, just in the main is getting the structData properly, what could I be missing here ?

the templates (start main end) was generated successfully with the hardcoded data, but the data which should come from structData, is not add during the generation to the start and end templates

Should I add the structData also to the start and end somehow ?

  • 写回答

1条回答 默认 最新

  • dongyan2445 2018-09-01 23:51
    关注

    When you use template to invoke another template, dot is not set by default, but you can pass the value as an (optional) second parameter to template like this:

    {{template "name"  pipeline}}
    

    In your case, your main.txt template should be

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

    to pass the value of dot down to the start and end template.

    Because the value of dot can be set this way, it is also possible to split templates up into multiple files in more complex ways. For example, you could have an HTML template to display the user information in a card-style fashion, and wherever you want to insert this card in your output, you can just invoke the template and pass it the user, even when the surrounding template needs other information as well or in a loop.

    For more details, check the text/template docs. This works both for text/template and html/template, but is only documented explicitly for text/template, while there is a note at the start of documentation for html/template telling you, where the detailed documentation can be found.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分