小胡子和把手上有什么真正的或虚假的? [英] What is truthy or falsy in Mustache and Handlebars?

查看:95
本文介绍了小胡子和把手上有什么真正的或虚假的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中:

  falsy:false,null,undefined,0,-0,NaN,
truthy:其他所有内容,包括[]和{}(空数组和空对象)

看起来像是(来自 Handlebars's文档 {{#if foo}}

  falsy:false,undefined,null,,[] 
truthy:其他所有内容,包括0,-0,{}

undefined NaN 不能作为JSON文件中的值列出,所以我无法使用Java Mustache渲染器对其进行测试,但是,如果我没有在所有,那么它可能只是 undefined ,它被视为虚假。



以上是 {{#if foo}} ,并且使事情更加复杂,Handlebars和Handlebars中的 {{#foo}} 在胡子?真假和伪造规则是否与 {{#if foo}} 完全相同?如果可能,请提供文档提示以支持您的声明。希望在PHP或Java或其他语言中实现Mustache或Handlebars遵循完全相同的规则。我还发现对于小胡子,看起来 {{#foo}} 被称为小节,其规则是:

  falsy:不管JavaScript中是否有错误,加上[] 
truthy:其他所有

但是看起来can.js的Mustache / Handlebars的实现将 0 视为虚假。 (请参阅 http://jsfiddle.net/kAt7E/45/ vs http://jsfiddle.net/kAt7E/46/ http://jsfiddle.net / kAt7E / 47 / vs http://jsfiddle.net/kAt7E/48/ )。所以这有点令人不安,因为有这么多不同的规则。

解决方案

根据Mustache规范,真实性取决于宿主语言。已有多个 尝试以跨语言标准化,但共识是宿主语言有最终的说。



在JavaScript中, !! val === true 的任何内容都是真实的,其中 !! val === false 是falsey。如果同一主机语言中不同的Mustache实现不一致地应用此规范,那么它就是实现中的一个错误。


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.

解决方案

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.

这篇关于小胡子和把手上有什么真正的或虚假的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆