Default value for a Handlebars` template placeholder

MTVS picture MTVS · Sep 1, 2014 · Viewed 17.8k times · Source

Can I specify a default value for a Handlebars` template placeholder?

<script type="x-handlebars-template" id="menu-edit-form-tpl">
    <form method="{{method}}" action="{{action}}" class="menu-edit-form">
...                     
    </form>
</script>

Can I specify default values for {{method}} and {{action}} and skip them in the object that is passed to the compiled template?

Answer

raidendev picture raidendev · Sep 4, 2014

Handlebars has no "default values".
You should use {{#if}} statement to check property is set.

<script type="x-handlebars-template" id="menu-edit-form-tpl">
    <form method="{{#if method}}{{method}}{{else}}POST{{/if}}" action="{{#if action}}{{action}}{{else}}/{{/if}}" class="menu-edit-form">
...
    </form>
</script>

Or if you want a bit cleaner syntax, use the simple helper:

Handlebars.registerHelper('safeVal', function (value, safeValue) {
    var out = value || safeValue;
    return new Handlebars.SafeString(out);
});

which allows you to write like this:

<script type="x-handlebars-template" id="menu-edit-form-tpl">
    <form method="{{safeVal method 'POST'}}" action="{{safeVal action '/'}}" class="menu-edit-form">
...
    </form>
</script>