Helper function and iteration

284 Views Asked by At

My input data is a comma-enumerated list, e.g. "en,fr,es" for a set of languages I speak. I want my template to render it as a list using ul/li.

I have defined a helper function that can transform the "en,fr,es" into an array ["en", "fr", "es"] using the Javascript split.

can.stache.registerHelper('split_comma', function(str, options) {
    return str.split(",");
});

But I cannot figure out how to make the template work?

Assuming the following context: { Language: "en,fr,es", languages: ["en", "fr", "es"] }

{{#each languages}} {{this}} and {{/each}}

returns the right stuff.

{{#each split_comma Language}} {{this}} and {{/each}}

does not return anything.

It seems that the helper function does not take precedence.

Am I missing something?

1

There are 1 best solutions below

1
On BEST ANSWER

As far as I know this is not how Handlebars helpers work. What you probably want to do is to introduce a new section with the split_comma helper that has the language array as the context:

can.stache.registerHelper('split_comma', function(str, options) {
    return options.fn(str.split(","));
});

and then iterate over that:

{{#split_comma Language}}
    {{#each .}} {{this}} and {{/each}}
{{/split_comma}}