Include template with dynamic name

I’m trying to include a template with a dynamic name.

I’m doing the following:

{{ template $template_to_import . }}

where $template_to_import cointains a string with the template path.

I’m getting the following error:

unexpected “$template_to_import” in template clause.

I can’t find a way to make it work.

Any ideas?

the way I understand Go Templates (could be wrong) that should be .$template_to_import - notice the dot.

I’ve just tried your suggestion with no luck:

unexpected bad character U+0024 '$' in template clause

Can you show more of the code? How did you create the var?

The syntax for that template call is to use a string, and the docs show it with quotes, so, you might try putting quotes around the variable.

 {{ template "$template_to_import" . }}

That error probably comes from some place where you use " in the markup that you copied from these forums. The forum somehow adds stylized " instead of the "normal “hyphen”.

I suspect the template keyword needs a constant value. It is evaluated when the templates are parsed, not when they are executed.

There should, however, be plenty of ways to get where you want to go – but it is hard to tell without any context.

1 Like

So, I’m getting the template name from a json file (course_name). Something like this:

{{ $data := index $.Site.Data.courses.course_name }}
{{ $part := $data.part }}

The $part variable contains a string with the relative template path.

It depends a little

  • Use partial if this is purely something standalone
  • Use .Render if this is somehow “page view” related

Both can be invoked dynamically.

Ok, using partial works fine.
The .Render method requires to be within a list context, according to this reference, am I right?

Thanks!

No, it requres a Page context. And in the latest Hugo it supports all page types (the docs may be a little out of date), and is really powerful if you can wrap your head around it.

2 Likes