Search code examples
templatesunderscore.js-templating

Underscore template - how to check multiple conditions


In my app, I am trying to check 2 conditions with the if part. But not working. I am not getting the result too..

here is my condition what i use :

<% _.each(recourseParameter, function (item, index) { %>

            <% if (index % limit == 0 )  { %>
                <%= _.template($('#header').html())({"parameterCode":parameterCode}) %>
            <% } %>

            <% if(item.description) { %>
                <tr>
                    <td colspan=5><%= item.description %></td>
                </tr>
            <% } %>

            <% if (((index+1) % limit == 0 ) && ((index +1) != limit)) { %> // this is not working!
                    <%= _.template($('#closer').html())() %>
                        <span>Continue ... </span> //this is not printing..
                    </div>
            <% }  %>

    <% }) %>

Live Demo


Solution

  • The if actually is working fine. The logic that the if code is trying to validate is incorrect.

    Let's have a look.

    <% if (((index+1) % limit == 0 ) && ((index +1) != limit))
    

    The possible value of index is 0 to 10 while the limit is always 9

    Now to satisfy this requirement (index+1) % limit == 0 the index must be 8, other than that the % won't be 0 since only (8+1) % 9 == 0.

    Now, the index is 8. The second condition in if is (index+1) != limit which (8+1) != 9 that would always return false.

    Thus, the <% if (((index+1) % limit == 0 ) && ((index +1) != limit)) would never return true.

    In summary, the if function is working perfectly, please modify the logic of the codes accordingly: