javascriptcanjs

How do I use variables in canJS?


Here is the code I am trying to play around with. In my JS file I have: $count = 0

In my HTML I am trying:

{{#if categories}}
<div id="categories">
  {{#each categories}}
  {{count = count + 1}}
  <div class="category" url="{{url}}">
    <div class="category-icon"></div>
    <div class="category-name">{{name}}</div>
    <span class="category-info"></span>
  </div>
  {{#if !(count%3)}}
		<br/>
	{{/if}}
  {{/each}}
</div>
{{/if}}

I want there to be a new line after every three categories I display - is there a way to do this with canJS?


Solution

  • You can add a simple helper everyThird and use @index helper provided with stache engine. Demo.

    helpers: {
        everyThird: function(val) {
            return val && val%3 === 0;
        }
    }
    

    inside template

      <ul>
      {{#each categories}}
        {{#if everyThird(@index)}}
         <li><hr></li>
        {{/if}}
        <li>{{name}}</li>    
      {{/each}}
      </ul>