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?
What is Handlebars? Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.
To have access to the passed arguments, you need to look for them into the 'hash' object: {{hash. foo}}. (I'm new with handlebars and this took me a while to figure out) - Thanks, great helper! Note, this requires you to have your partials pre-compiled before using the helper.
Helpers can be used to implement functionality that is not part of the Handlebars language itself. A helper can be registered at runtime via Handlebars. registerHelper , for example in order to uppercase all characters of a string.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With