Search code examples
javascriptjqueryhtmlunderscore.js-templating

How to show a div in JS underscore template


I am using $.getJSON in a jquery script to get data from a php file and display it in a template(underscore).

My template:

<script type="text/template" id="user-template">

<% _.each(users, function(user){%>
            <div class="id"><%=user.id%> </div>
            <div class="name"><%= user.name %></div>
            <div class="city"><%= user.city %></div><br />
    <% }); %>

</script>

My script:

$.getJSON(url, function(data){
        var results = userTemplate({ users: data.users}),
        $("#theresults").html(results);}

On each page im listing 10 users (or 10 results). The code works fine. I want to be able to show another div after every 4 results. Like an ad or a promotional content.

<div id="mycustomdiv">Custom DIV</div>

How do i do that?

Thanks.


Solution

  • Just use the second argument of the callback function to determine the current index

     <% _.each(users, function(user, index){%>
            <div class="id"><%=user.id%> </div>
            <div class="name"><%= user.name %></div>
            <div class="city"><%= user.city %></div><br />
            <% if(index !== 0 && (index % 4) === 0) { %>
               <div id="mycustomdiv">Custom DIV</div>
            <% } %>
     <% }); %>