Brayden
Brayden

Reputation: 155

Evaluating Expression in Function call

I have this function call that makes a checkbox

{{checkbox "checkbox_{{id}}" }}

but as you might have guessed, the result I get, is

<input type="checkbox" name="checkbox_{{id}}" id="checkbox_{{id}}">

Im looking for it to evaluate the {{id}} in the function call.

Upvotes: 2

Views: 542

Answers (1)

gfullam
gfullam

Reputation: 12045

Just pass the id

Pass in id and have the helper append it to the name and id attributes with whatever prefix you want.

Template

{{{checkbox id}}}

Helper

// Expression Helper
Handlebars.registerHelper('checkbox', function (id) {
    return '<input type="checkbox" name="checkbox_' + id + '" id="checkbox_' + id + '">';
});

JS Fiddle: http://jsfiddle.net/gfullam/390t5cnh/


UPDATE: It's worth noting that Handlebars will not evaluate a mustache inside of a mustache. But...

Subexpressions

Handlebars offers support for subexpressions, which allows you to invoke multiple helpers within a single mustache, and pass in the results of inner helper invocations as arguments to outer helpers. Subexpressions are delimited by parentheses.

{{{checkbox (myOtherHelper id)}}}

Multiple arguments

You may also pass in multiple arguments to a single helper:

Template

{{{checkbox "checkbox_" id}}}

Helper

// Expression Helper
Handlebars.registerHelper('checkbox', function (prefix, id) {
    return '<input type="checkbox" name="' + prefix + id + '" id="' + prefix + id + '">';
});

Upvotes: 2

Related Questions