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 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R