MTVS MTVS - 2 months ago 31
Javascript Question

Default value for a Handlebars` template placeholder

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?

rd5 rd5
Answer

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>