Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars doesn't render boolean variables when false

Handlebars.js has some weird behavior. It renders a boolean with a value of true as the string "true", but a value of false as "".

var booleanTestTrue = true;
var booleanTestFalse = false;

Template:

True: {{booleanTestTrue}}
False: {{booleanTestFalse}}

Renders to:

True: true
False: (empty string)

Is there any way to fix this problem? Or do I have to write a helper?

like image 947
ccleve Avatar asked Jul 15 '13 21:07

ccleve


People also ask

Are Handlebars 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.

How do you use unless Handlebars?

You can use the unless helper as the inverse of the if helper. Its block will be rendered if the expression returns a falsy value. If looking up license under the current context returns a falsy value, Handlebars will render the warning. Otherwise, it will render nothing.

What does variable triple brace meaning in Handlebars?

Because it was originally designed to generate HTML, Handlebars escapes values returned by a {{expression}} . If you don't want Handlebars to escape a value, use the "triple-stash", {{{ . Source: https://handlebarsjs.com/guide/#html-escaping.


3 Answers

You can use a simple block helper and implement #if like the following:

{{#if isTrue}}
       true
{{else}}
       false
{{/if}}
like image 143
Aaks20 Avatar answered Oct 26 '22 11:10

Aaks20


If you want to print a string, you should pass a string.

false.toString();

Otherwise, yeah you would need a helper (unless you use the #if|#unless helpers to output a string).

On a side note, if you wanted to print these values for debugging purpose, use the {{log booleanTestFalse}}.

like image 30
Simon Boudrias Avatar answered Oct 26 '22 12:10

Simon Boudrias


I was surprised by this, and ended up writing a simple helper for it:

Handlebars.registerHelper( 'toString', function returnToString( x ){
    return ( x === void 0 ) ? 'undefined' : x.toString();
} );

You would then invoke it as follows:

True:  {{toString booleanTestTrue}}
False: {{toString booleanTestFalse}}

In most scenarios you could get away with simply return x.toString(). The extra checking avoids attempting to call toString on undefined values.

like image 3
Barney Avatar answered Oct 26 '22 12:10

Barney