Search code examples
javascriptjsondot.js

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?


Solution

  • 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 }}