Home > Mobile >  Go template post processing: is it possible?
Go template post processing: is it possible?

Time:10-21

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?

{{ 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?

{{$var := execTempl "subtemplate"}}
{{$var}}

CodePudding user response:

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.

var externalTemplates = map[string]*template.Template{
    "subtemplate": template.Must(template.New("subtemplate").Parse(sub_template)),
}

// Executes external template, must be registered with FuncMap in the main template.
func xtemplate(name string) (string, error) {
    var b bytes.Buffer
    if err := externalTemplates[name].ExecuteTemplate(&b, name, nil); err != nil {
        return "", err
    }
    return b.String(), nil
}
t := template.Must(template.New("t").Funcs(template.FuncMap{
    "xtemplate": xtemplate, // register func
}).Parse(main_template))

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

{{ xtemplate "subtemplate" | indent 10 }}

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

  • Related