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")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里