Simplest way to get current item index within jQuery template

serg picture serg · Oct 9, 2010 · Viewed 20.6k times · Source

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...

Answer

kdawg picture kdawg · Nov 2, 2010

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.