Handlebars.js 如果块助手 == [英] Handlebars.js if block helper ==

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

问题描述

您将如何更改以下代码以使其工作?问题是 this == 'some message' 表达式:

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>

推荐答案

最简单的方法是添加一个自定义的 if_eq 助手:

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);
});

然后调整您的模板:

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

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

如果您的 errors 条目不是简单的字符串,那么您可以向它们添加这是一些消息"标志并使用标准的 {{#if}} (请注意,将属性直接添加到字符串中效果不佳):

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' };

和:

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

演示:http://jsfiddle.net/ambiguous/9sFm7/

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

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