Handlebars doesn't render boolean variables when false

会有一股神秘感。 提交于 2019-12-03 04:31:43
Aaks20

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

{{#if isTrue}}
       true
{{else}}
       false
{{/if}}

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}}.

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.

I used this, similar to Barney's answer but supports null too.

Handlebars.registerHelper('toString', function (v) { 
    return '' + v; 
});

You would then invoke it as follows:

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

However if v is an object with a pretty toString method you need to do more coding.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!