本文介绍了把手#if和数字零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  {{{}}在我的Handlebars模板中,我检查是否存在一个变量, #if foo}} 
某些文本
{{/ if}}

如果foo是文本或者foo是数字而不是零,这可以正常工作。但是,如果

  var foo = 0; 

然后 {{#if foo}} 返回false。



这似乎是另一个Javascript的怪胎,因为Javascript本身的行为方式是一样的。但是,在Javascript代码中,您可以通过检查变量是否未定义来解决此问题。

我如何在Handlebars中做同样的事情?



我可以写一个 {{#exists}} helper,但我希望有内置的东西。

解决方案

我会更好地为{{else}}条件提供一个案例...

  / ** 
* {{#exists}}帮助程序检查是否定义了一个变量。
* /
Handlebars.registerHelper('exists',function(variable,options){
if(typeof variable!=='undefined'){
return options.fn( this);
} else {
return options.inverse(this);
}
});

现在您可以拥有:

<$ p $ myvar的值是... {{myvar}}< / p>
{{else}}
< p>请提供myvar< / p>
{{/ exists}}


In my Handlebars template I check for the existence of a variable, and render some text if it's there:

{{#if foo}}
  some text
{{/if}}

This works fine if foo is text or if foo is numeric but not zero. But if

var foo = 0;

then {{#if foo}} returns false.

This appears to be yet another Javascript oddity, because Javascript itself behaves the same way. In Javascript code, though, you could get around this by checking if the variable is 'undefined'.

How can I do the same thing in Handlebars?

I could write an {{#exists}} helper, but I was hoping there was something built in.

解决方案

I would go one better and provide a case for the {{else}} condition...

/**
 * The {{#exists}} helper checks if a variable is defined.
 */
Handlebars.registerHelper('exists', function(variable, options) {
    if (typeof variable !== 'undefined') {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

Now you can have:

{{#exists myvar}}
  <p>Value of myvar is ... {{myvar}}</p>
{{else}}
  <p>Please supply a myvar</p>
{{/exists}}

这篇关于把手#if和数字零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 10:17