I am passing an array of objects to jQuery template (official jquery-tmpl plugin):
$("#itemTmpl").tmpl(items).appendTo("body"); <script id="itemTmpl" type="text/x-jquery-tmpl"> <div class="item">Name: ${name}, Index: ${???}</div> </script> What is the easiest way to display item index in the template? Preferably without using separated external functions, without changing passed object structure, and without changing template structure (converting to {{each}}). Is there any built-in variable perhaps that stores current array index?
UPDATE I created a ticket proposing to expose array index to template item but it was closed as invalid...
Well, it's not a true separate external function, but you can slap a function onto the options object you can pass to tmpl. I've done the following and it works fine:
$("#templateToRender").tmpl(jsonData, { dataArrayIndex: function (item) { return $.inArray(item, jsonData); } }); In the template, you can access the function from the $item object:
<script id="templateToRender" type="text/x-jquery-tmpl"> <li> Info # ${$item.dataArrayIndex($item.data)} </li> </script> Alternatively, instead of passing $item.data into the function, the context of the function is the tmplItem object of the template (same as $item.data). So you could write dataArrayIndex as parameterless and access the data via this.data.
Here's a cheezy hack:
${ _index === undefined && _index = 0, '' } <strong>Item ${ index }:</strong> ${ content } ${ _index++, '' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With