Dynamically constructing template name

I’m trying to use Template.dynamic. The docs say:

Template.dynamic allows you to include a template by name, where the name may be calculated by a helper and may change reactively.

I want to use a helper, like it describes, but I want to pass an argument (in this case my current data context) to that helper, e.g.:

{{> Template.dynamic template=(getTemplateName this) }}

The above syntax doesn’t compile (due to the parends, presumably; I thought I’d seen spacebars support parentheses-grouping in some cases) and I can’t find any version of it that does.

In this case, my getTemplateName helper is really just doing string concatenation, to namespace the dynamically-called templates with the name of the template they’re being called from:

  getTemplateName: function(data) {
    return "myOuterTemplateName-" + data.id;

(I don’t want templates in the global template namespace that are just the values of data.id).

I also hoped I could just inline-string-concatenate, but that doesn’t seem to work either:

{{> Template.dynamic template="myOuterTemplateName-"+id }}
{{> Template.dynamic template=("myOuterTemplateName-"+id) }}

or at least I can’t find a way to get it to work.

I thought I’d read about a #let statement somewhere, that I could imagine being useful here, but am having trouble google-finding it now.

Is there no way to pass arguments to helpers to populate the template argument?

Thanks for your help in advance!

Doesn’t using this in the helper work in this case? (As this represents the data context.)

{{> Template.dynamic template=getTemplateName}}
getTemplateName: function() {
  return "myOuterTemplateName-" + this.id;

Or you can pass a data context to the helper using data=dataContext if you need to. See the docs here.

1 Like

Your first suggestion is exactly what I want, thanks @babrahams; I skipped that day of handlebars class and that will be useful to me in many contexts.

FWIW I don’t think your second suggestion is correct; that data argument sets the context for the dynamically-selected template, not the helper that I’m calling to select said template; lmk if I’m mistaken.

Haha… yes, you’re right. I should have read the docs more carefully.