Handlebars if statement with index = some value

て烟熏妆下的殇ゞ 提交于 2019-12-05 05:30:35
context.length/5 == 0 

will not give you the value you want every 5th element. As 5/5 is 1, better to use modulus(%) which gives you the remainder, this way when it equals 0 you know it has gone into it whole.

Also when wanting to do your own if/else block handle bars provides you with options.fn and options.inverse. Return options.fn(//whatever you want to pass to the if block) or options.inverse(//what ever to provide to the else block) from your helper to go into the relevant part of the block.

Here is a code pen showing a quick example of how you could get the index position of the element you are iterating over and apply a styling based on that. The helper functions will go to the true part of the if block when index % 3 is 0 (the first, because it is a 0 based index, and then every 3rd element. All other times it will go to the else

Helper

Handlebars.registerHelper('ifThird', function (index, options) {
   if(index%3 == 0){
      return options.fn(this);
   } else {
      return options.inverse(this);
   }

});

Template

<script id="template" type="text/x-handlebars-template">

      {{#each this}}
      <p class="{{#ifThird @index}}
                  red
                {{else}}
                  blue
                {{/ifThird}}">{{@index}} - {{name}}</p>
      {{/each}}

</script>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!