Handlebars.js if block helper == [英] Handlebars.js if block helper ==

查看:170
本文介绍了Handlebars.js if block helper ==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何改变下面的代码使其工作?问题是this =='some message'表达式:

 < ul> 
{{#each errors}}
{{#if(this =='some message')}}
< li>状态< / li>
{{else}}
< li> {{this}}< / li>
{{/ if}}
{{/ each}}
< / ul>


解决方案

最简单的事情是添加一个自定义 if_eq helper:

  Handlebars.registerHelper('if_eq',function(a, b,opts){
if(a == b)// Or ===根据您的需要
return opts.fn(this);
else
return opts。 inverse(this);
});

然后调整您的模板:

 {{#if_eq thissome message}} 
...
{{else}}
...
{{/ if_eq}}

演示: http://jsfiddle.net/ambiguous/d4adQ/

如果您的错误

code>条目不是简单的字符串,那么你可以添加这是一些消息标志给他们,并使用标准的 {{#if}} 直接添加属性到一个字符串将无法正常工作):

  for(var i = 0; i  errors [i] = {msg:errors [i],is_status:errors [i] ==='some message'}; 



  {{#if is_status}} 
< li>状态< / li>
{{else}}
< li> {{msg}}< / li>
{{/ if}}

演示:

How would you change the following code to make it work? The problem is the this == 'some message' expression:

<ul>
  {{#each errors}}
    {{#if (this == 'some message') }}
    <li>Status</li>
    {{else}}
    <li>{{this}}</li>
    {{/if}}
  {{/each}}
</ul>

The easiest thing would be to add a custom if_eq helper:

Handlebars.registerHelper('if_eq', function(a, b, opts) {
    if(a == b) // Or === depending on your needs
        return opts.fn(this);
    else
        return opts.inverse(this);
});

and then adjust your template:

{{#if_eq this "some message"}}
    ...
{{else}}
    ...
{{/if_eq}}

Demo: http://jsfiddle.net/ambiguous/d4adQ/

If your errors entries weren't simple strings then you could add "is this some message" flags to them and use a standard {{#if}} (note that adding a property directly to a string won't work that well):

for(var i = 0; i < errors.length; ++i)
    errors[i] = { msg: errors[i], is_status: errors[i] === 'some message' };

and:

{{#if is_status}}
    <li>Status</li>
{{else}}
    <li>{{msg}}</li>
{{/if}}

Demo: http://jsfiddle.net/ambiguous/9sFm7/

这篇关于Handlebars.js if block helper ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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