问题
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