Go模板后处理:是否可能?

huangapple go评论115阅读模式
英文:

Go template post processing: is it possible?

问题

在我的模板中,我使用了一个生成输出片段的子模板。
但是模板输出必须进行偏移(因为输出是YAML格式)。
有没有可能对模板输出进行后处理?

  1. {{ template "subtemplate" | indent 10 }}

这里的 indent 10 是虚构的,只是为了解释我需要的内容。

可以(如@icza建议的那样)将输出保存到一个变量中,然后再处理它,
但也许有更好、更优雅的方法?

  1. {{$var := execTempl "subtemplate"}}
  2. {{$var}}
英文:

In my template, I use a sub-template that generates a piece of output.
The template output must be shifted though (because the output is in YAML format).
Is there any possibility to post-process template output?

  1. {{ template "subtemplate" | indent 10 }}

This indent 10 is fictional, just to explain what I need.

It is possible (as @icza suggested) to save the output
into a variable and then work with it,
but maybe there is a better, more elegant approach?

  1. {{$var := execTempl "subtemplate"}}
  2. {{$var}}

答案1

得分: 1

你可以通过定义一个函数来实现与 {{ template "subtemplate" | indent 10 }} 最接近的效果,该函数解析并执行 subtemplate,并将结果输出为字符串。

  1. var externalTemplates = map[string]*template.Template{
  2. "subtemplate": template.Must(template.New("subtemplate").Parse(sub_template)),
  3. }
  4. // 执行外部模板,必须在主模板中使用 FuncMap 进行注册。
  5. func xtemplate(name string) (string, error) {
  6. var b bytes.Buffer
  7. if err := externalTemplates[name].ExecuteTemplate(&b, name, nil); err != nil {
  8. return "", err
  9. }
  10. return b.String(), nil
  11. }
  1. t := template.Must(template.New("t").Funcs(template.FuncMap{
  2. "xtemplate": xtemplate, // 注册函数
  3. }).Parse(main_template))

在主模板中,你可以像这样使用该函数:

  1. {{ xtemplate "subtemplate" | indent 10 }}

https://play.golang.org/p/brolOLFT4xL

英文:

The closest you can get to {{ template "subtemplate" | indent 10 }} is to define a function that parses and executes the subtemplate and outputs the result as string.

  1. var externalTemplates = map[string]*template.Template{
  2. "subtemplate": template.Must(template.New("subtemplate").Parse(sub_template)),
  3. }
  4. // Executes external template, must be registered with FuncMap in the main template.
  5. func xtemplate(name string) (string, error) {
  6. var b bytes.Buffer
  7. if err := externalTemplates[name].ExecuteTemplate(&b, name, nil); err != nil {
  8. return "", err
  9. }
  10. return b.String(), nil
  11. }
  1. t := template.Must(template.New("t").Funcs(template.FuncMap{
  2. "xtemplate": xtemplate, // register func
  3. }).Parse(main_template))

In the main template you can then use the function like this:

  1. {{ xtemplate "subtemplate" | indent 10 }}

https://play.golang.org/p/brolOLFT4xL

huangapple
  • 本文由 发表于 2021年10月21日 21:06:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/69662568.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定