Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 975
MTVS Avatar asked Sep 01 '14 09:09

MTVS


People also ask

What is Handlebars 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.

How do you pass variables to Handlebars?

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.

What are helpers in Handlebars?

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.


1 Answers

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> 
like image 76
raidendev Avatar answered Sep 22 '22 13:09

raidendev