dpi96151 2018-06-04 20:07
浏览 138
已采纳

在Golang中结合使用模板块和模板函数

I'm looking to use template blocks in Golang to get a "template inheritance" style overwrite logic.

I have a base.html template which is something like this:

<title>{{block "title" .}}Default Title{{end}}</title>
<body>{{block "content" .}}This is the default body.{{end}}</body>

And then I have a template blogpost.html like so:

{{define "title"}}Blog Post Title{{end}}
{{define "content"}}Lorem Ipsum...{{end}}

All of this works flawlessly as long as I just use ParseFiles and then execute the template

t, err := template.ParseFiles("./templates/base.html", "./templates/blogpost.html")
t.Execute(t, viewModel)

The way I did it was calling ParseFiles once for every template I needed to render. E. g. I did not call templates by name.

However, I now want to also use Template Functions. Now I need to call template.New to get an empty template, assign a name, add the template functions and parse the files (Funcs "must be called before the template is parsed") :

tpl := template.Must(
    template.New("somename").Funcs(sprig.FuncMap()).ParseGlob("*.html")
)

This seems to be incompatible with my idea of template inheritance. I have to ExecTemplatewith my base.html as a parameter in order to get any output. However, I'd like to load one base template and many content templates. Then call the content templates by name.

Am I misunderstanding the way that Golang templates and/or Blocks are intended to be used? What's an elegant and idiomatic way to perform this kind of task?

  • 写回答

1条回答 默认 最新

  • doutongya8378 2018-06-04 21:12
    关注

    Use the following to add template functions to what you already have working:

    t, err := template.New("base.html").Funcs(sprig.FuncMap()).ParseFiles("./templates/base.html", "./templates/blogpost.html")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料