Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to get current item index within jQuery template

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

like image 961
serg Avatar asked Oct 09 '10 01:10

serg


2 Answers

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.

like image 105
kdawg Avatar answered Sep 28 '22 18:09

kdawg


Here's a cheezy hack:

${ _index === undefined && _index = 0, '' } <strong>Item ${ index }:</strong> ${ content } ${ _index++, '' } 
like image 42
a paid nerd Avatar answered Sep 28 '22 19:09

a paid nerd