We can define template name via {{define "home"}}
, and then load it in other (parent) template via {{template "home"}}
.
How I can load template via variable value {{template .TemplateName}}
. Or it's impossible?
We can define template name via {{define "home"}}
, and then load it in other (parent) template via {{template "home"}}
.
How I can load template via variable value {{template .TemplateName}}
. Or it's impossible?
Unfortunately you can't.
The syntax of the
{{template}}
action:The name of the template to be included is a constant string, it is not a pipeline which could vary during execution based on parameters.
If the allowed syntax would be:
then you could use something like
{{template .TemplName}}
but since the syntax only allows a constant string, you can't.Reasoning from Rob why dynamic template invocation is not allowed (source):
Alternative #1: Execute Includable Template First
What you can do is execute the template you would want to include first, and insert the result where you want to include it. You can use special types not to escape the result of the inner template when inserting, for example
html.HTML
in case of HTML templates.See this example:
Output:
Try it on the Go Playground.
The result of template
t1
was inserted unescaped. If you leave outtemplate.HTML
:t1
would be inserted escaped, like this:Alternative #2: Restructure Templates
You can restructure your templates not to be in situations where you would want to include a template with varying names.
Example: you might want to create pages where you have a
page
template something like this:You can restructure it to be something like this:
header
template:footer
template:And your page templates would include
header
andfooter
like this:Alternative #3: Use
{{if}}
action and predefined namesIf you know the template names prior and it is not an exhausting list, you can use the
{{if}}
template action to include the desired template. Example:Alternative #4: Modifying the static template text
The idea here is that you could modify the static text of the outer template manually and insert the name of the inner template you want to include.
The downside of this method is that after inserting the name of the inner template, you have to re-parse the template, so I don't recommend this.