Simplest way to get current item index within jQuery template Simplest way to get current item index within jQuery template jquery jquery

Simplest way to get current item index within jQuery template


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++, '' }


Just ran into this issue myself. very frustrating! The index of the template item for example was always available in jTemplates.Shouldnt have been difficult to add that in i would think...

Weird thing is that in Firebug I can see the key property for each $item:item key

But when trying to access it from a function i call from within the template:

<img class="profImage" src="${getProfileImage($item)}" />

In the function if I check the item key property either like 'item.key' or '$(item).key' I get 'undefined' and not the actual value...