Dynamic templating facilitated through gomplate
Using `Template.Exec`` to facilitate dynamic templating with gomplate
Table Of Contents
Today I Explained
gomplate is a template renderer CLI that can fit nicely within the niche of lightweight templating solution, as it’s support for datasources (like JSON & YAML) and conditional execution pushes it a step up above hand-crafting something in PowerShell or Bash. One of the frustrations that arises with this method of templating is the difficulty with debugging the execution of the conditional logic.
A solution to workaround this is the adoption of the template.Exec
function within gomplate. This function allows for executing (rendering) a named template, for which the result can be written to a file using file.Write
. This allows one to push the responsibility of “complex” logic to be performed within a run.tpl
(or exec.tpl
) template, which emits both a log result, and the rendered document. In practice this will look like:
# run.tpl
Log: Gomplate Run
{{ ctx := map ... }}
{{ computedResult := ... }}
Computed Result: {{ $computedResult }}
{{ if (ds "mydata").system.enabled }}
# Render the named template "named", and write it to the file "result.txt"
{{ template.Exec "templates/named" $ctx | file.Write "result.txt" }}
{{ end }}
The primary output of run.tpl
is the logging file (debug) for the template conditions, allowing for better diagnosing, as well as invoking any of the named templates used by the gomplate run. This works in both cases where you have a single rendered document, or multiple rendered documents as outputs.
A note on Code vs. Script
Sometimes when working with template renderer CLIs like gomplate, it can seem inappropriate or something that should be really be written in a programming language (e.g. a quick main.go
). In some cases this can be correct, but this isn’t always the case. As many times the reason for the complexity of the template growing out of control, is due to the structure of the provided input. Writing the template within a programming language allows for data manipulation which allows working around the data problem, when sometimes it might be best to revisit the schema of the data provided.
This isn’t always possible, but it’s something to consider when a template is becoming far more significant and difficult to maintain.