Flügge Flügge - 4 years ago 173
Javascript Question

doT.js do something every 3rd iteration

I have a doT.js template looking like this:

{{?it.books.length }}
{{~it.books :value}}
<li>
<article class='Teaser'>
<a href='{{=value.url}}' title='{{=value.title}}'>
<img src='{{=value.image}}' />
</a>
<h3>
<a href='{{=value.url}}' title='{{=value.title}}'>{{=value.title}}</a>
</h3>
</article>
</li>
// this should only be rendered every 3rd time
<br class='clear' />
{{~}}
{{?}}


The br-Tag in the end should only be rendered every third time. How do I do this?

Answer Source

Try this:

{{?it.books.length }}
{{~it.books :value:index}}
<li>
    <article class='Teaser'>
        <a href='{{=value.url}}' title='{{=value.title}}'>
            <img src='{{=value.image}}' />
        </a>
        <h3>
            <a href='{{=value.url}}' 
                title='{{=value.title}}'>{{=value.title}}</a>
        </h3>
    </article>
</li>
{{? index % 3 == 2 }}
<br class='clear' />
{{?}}
{{~}}
{{?}}

If you want to avoid adding the element at the end of the list (which occurs when the collection's length is divisible by 3), replace

{{? index%3 == 2 }}

with

{{? it.books.length-1 != index && index % 3 == 2 }}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download