有条件的“如果陈述” Handlebars.js的帮手 [英] Conditional "if statement" helper for Handlebars.js

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

问题描述

我正在为Handlebars.js写一个条件if语句帮助器。从本质上讲,如果它是立即申请页面,我想在链接上放置一个活跃类。



Helper:
$ b $ pre $ Handlebars.registerHelper('isApplyNow',function(block){
if(this.title ==
return block(this);
} else {
return block.inverse(this);
}
});



和模板:

 < ul> 
{{#each pages}}
< li>
{{#isApplyNow}}
{{else}}
< a href ={{url}}> {{this.title}}< / a>
{{/ if}}
< / li>
{{/ each}}
< / ul>

但是,我收到了一个非常糟糕的javascript错误:

 在handlebars-1.0.0.beta.2.js中未捕获[object Object]:595 

任何人都可以看到我是否写得不当?

谢谢!



参考文章:

如果在手柄模板中阻塞,则调用助手

http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/

解决方案

我确实看到一个小的语法错误,我认为这可能是问题所在。如果你打算使用一个带有块的助手,那么你必须用助手名称来关闭它。看看我如何用 {{/ isApplyNow}} 替换 {{/ if}} ,如下所示:

  {{#isApplyNow}} 
< a href ={{url}}class ='active > {{this.title}}< / A>
{{else}}
< a href ={{url}}> {{this.title}}< / a>
{{/ isApplyNow}}


I am trying to write a conditional if statement helper for Handlebars.js. Essentially, I want to put an "active" class on a link if it is the Apply Now page.

Helper:

  Handlebars.registerHelper('isApplyNow', function(block) {
    if(this.title == "Apply Now") {
      return block(this);
    } else {
      return block.inverse(this);
    }
  });

And Template:

  <ul>
    {{#each pages}}
      <li>
        {{#isApplyNow}}
          <a href="{{url}}" class ='active'>{{this.title}}</a>
        {{else}}
          <a href="{{url}}">{{this.title}}</a>
        {{/if}}
      </li>
    {{/each}}  
  </ul>

But, I am getting a very bare-bones javascript error:

Uncaught [object Object] in handlebars-1.0.0.beta.2.js:595

Can anyone see if I am writing this improperly?

Thanks!

Referenced articles:

Calling Helper Within If Block in Handlebars Template

http://thinkvitamin.com/code/handlebars-js-part-2-partials-and-helpers/

解决方案

I do see one minor syntax mistake which I believe could be the issue. If you are going to use a helper that takes a block, then you have to close it with the helper name. See how I've replaced your {{/if}} with {{/isApplyNow}}, like so:

    {{#isApplyNow}}
      <a href="{{url}}" class ='active'>{{this.title}}</a>
    {{else}}
      <a href="{{url}}">{{this.title}}</a>
    {{/isApplyNow}}

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

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