Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

templates - Handlebars.js if block helper ==

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...