views:

128

answers:

2

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

+1  A: 

There is no easily accessible index. There is a key that is appended to each item.

<div class="item" jQuery1287500528620="1">

This key is accessible through jquery. So you can do something like

$(".item").each(function () {
                var theTemplate = $(this).tmplItem();
                $(this).append("Index: " + theTemplate.key);
            });

But that's not what you wanted. I don't think what you wanted is possible. The ${$item} object is supposed to represent the tmplItem() method, but it doesn't provide a value for ${$item.key}. Using ${$.tmplItem().key} produces 0 for each row.

So the answer to your question is..... No.

Tom B