How do i count the items in a each jquery template and the apply a if to that variable
something like
<script id="inventorySummaryTmpl" type="text/x-jquery-tmpl">
<tr>
{{each response}}
{{if response.length === 2 }}
</tr><tr>
{{/if}}
<td><img src='${icon}'> ${title} </td>
{{/each}}
</tr>
This is the javascript that loads the JSON and interacts with the jquery.TMPL
var ip = window.location.hash;
var request = $.ajax({
type: 'GET',
url: 'ajax/dashboard/widgets/inventorySummary.xsp?ip='+ip.substring(1),
dataType: 'json'
});
request.done(function(data){
$("#inventorySummaryTmpl").tmpl(data).appendTo("#inventorySummaryContent");
});
request.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log(textStatus)
});
And the JSON
{
"response": [
{
"icon": "workstation",
"nbItems": "38",
"title": "Workstations"
},
{
"icon": "server",
"nbItems": "2",
"title": "Servers"
}
]
}
if someone has any ideeas.
You were pretty close. The variable in the
eachstatement needs to be the full collection you are looping through. You can also pass custom variable names for the index and value of each item in the collection. Based on your code, the following should work, but if you posted the structure of your collection, we’d be able to ensure that it doesjQuery Docs: http://api.jquery.com/template-tag-each/
UPDATE
I’ve updated my solution now that I see what you’re after. If you want to start a new
ul(ortr) after every three (or six, or whatever) elements in theresponsearray, check the index of the current element, not the length of the full response array.DEMO: http://jsfiddle.net/jackwanders/ZzddF/1/