Search code examples
javascriptjqueryunderscore.jsunderscore.js-templating

Underscore template iteration with `tr` element on different datas giving wrong result


In my template, I have 5 headings, I am using "th" for that. and I would like to print two different datas underneath. for that i tried this but giving wrong out put...

any one help me to sort this pleae?

    <% _.each(obj.totalForMonths.totalformonths.monthData, function(item) { %> //data 1
                            <tr> //printing 3 tds
                                <td><%= item.month %></td>
                                <td><%= item.amount %></td>
                                <td><%= item.count %></td>

                            <%  }) %>

                            <% _.each(obj.totalForMonths.previousScheme.monthData, function(item) { //data 2 %>
//printing 2 tds!
                                    <td><%= item.amount %></td>
                                    <td><%= item.count %></td>

                            <%  }) %>

                            </tr>   //closing the tr after appended all 5

but it works as, first it loops all 3 and 2 loops separately. It gives ugly out put. How can i print all five within tr on each iterators?

Any one help me please?


Solution

  • You could merge the arrays "obj.totalForMonths.totalformonths.monthData" & "obj.totalForMonths.previousScheme.monthData" if they are of the same length:

        <% 
            var a = _.map(obj.totalForMonths.totalformonths.monthData, function(e){
                return [e.month, e.amount, e.count]
            });
            var b = _.map(obj.totalForMonths.previousScheme.monthData, function(e){
                return [e.amount, e.count]
            });
            rows = _.map(_.zip(a,b), function(e){
                return _.flatten(e)
            });
        %>
        <% _.each(rows, function(row) { %>
            <tr>
                <% _.each (row, function(column){ %>
                    <td><%= column %></td>
                <% }) %>            
            </tr>
        <%  }) %>