Jordon Bedwell
Jordon Bedwell

Reputation: 3247

Using a Go Template var inside of a `{{ template }}`

In Go we can create a variable easily enough with

{{- if .Bool.Var -}}
  {{ $MyVar := "val" }}
{{- end -}}

We can even create shared snippets easily enough

{{- define "val" -}}
  <p>Some shared template data</p>
{{- end -}}

My question is, how do we go about using $MyVar as a text value for {{template}} so that we can do something like {{template $MyVar}}, without causing an error, or is this not possible?

Upvotes: 1

Views: 709

Answers (1)

David Maze
David Maze

Reputation: 159810

In the pure Go text/template language (which is not Go per se but something different which happens to be implemented in Go) this isn't possible; the {{template}} invocation takes a literal string name.

One of the most prominent users of this language is the Kubernetes Helm deployment manager. That includes several extensions to the template language. One of those is an include template function that can take any value as the name of the template, and produces a string rather than immediately outputting the template contents (you can include it in a pipeline, which you can't with template). So specifically in a YAML file, you could

{{ include $MyVar }}

Upvotes: 1

Related Questions