What is truthy or falsy in Mustache and Handlebars?

时光总嘲笑我的痴心妄想 提交于 2019-12-23 09:04:50

问题


In JavaScript:

falsy: false, null, undefined, 0, -0, NaN, ""
truthy: everything else, including  [] and {}  (empty array and empty object)

But in Handlebars, it seems like it is (from Handlebars's docs) for {{#if foo}}:

falsy: false, undefined, null, "", []
truthy: everything else, including 0, -0, {}

undefined and NaN cannot be listed as a value in a JSON file, so I can't test it using a Java Mustache renderer, although, if I don't define a property at all, then it is probably just undefined and it is taken as falsy.

The above is for {{#if foo}}, and to make things more complicated, what about just {{#foo}} in Handlebars and in Mustache? Are the truthy and falsy rules exactly the same as {{#if foo}}? If possible, please provide pointers to docs to support your claim. Hopefully, implementation of Mustache or Handlebars in PHP or Java or other languages follow the exact same rules.

I also found that for Mustache, it seems {{#foo}} is called a section, and its rule is:

falsy: whatever falsy in JavaScript, plus []
truthy: everything else

But it seems that can.js's implementation of Mustache/Handlebars treats 0 as falsy. (See http://jsfiddle.net/kAt7E/45/ vs http://jsfiddle.net/kAt7E/46/ or http://jsfiddle.net/kAt7E/47/ vs http://jsfiddle.net/kAt7E/48/). So this is somewhat disturbing to have so many different rules.


回答1:


Per the Mustache spec, truthiness is dependent on the host language. There have been multiple attempts to standardize this across languages, but the consensus was that the host language had the final say.

Meaning, in JavaScript, anything for which !!val === true is truthy, and anything where !!val === false is falsey. If different Mustache implementations in the same host language inconsistently apply this spec, it's a bug in the implementation.



来源:https://stackoverflow.com/questions/21444525/what-is-truthy-or-falsy-in-mustache-and-handlebars

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