Skip to content

Commit

Permalink
adds an "$index" property (similar to the each tag) to the data item …
Browse files Browse the repository at this point in the history
…passed to nested templates using the {{tmpl}} tag

fixes: https://github.com/jquery/jquery-tmpl/issues#issue/28
  • Loading branch information
clarkbox committed Dec 14, 2010
1 parent 9b05e4a commit 993e6fa
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion jquery.tmpl.js
Expand Up @@ -144,7 +144,8 @@
updateWrapped( options, options.wrapped ); updateWrapped( options, options.wrapped );
} }
ret = jQuery.isArray( data ) ? ret = jQuery.isArray( data ) ?
jQuery.map( data, function( dataItem ) { jQuery.map( data, function( dataItem, index ) {
if(dataItem){dataItem.$index = index;}
return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
}) : }) :
[ newTmplItem( options, parentItem, tmpl, data ) ]; [ newTmplItem( options, parentItem, tmpl, data ) ];
Expand Down

3 comments on commit 993e6fa

@recalde
Copy link

@recalde recalde commented on 993e6fa Jan 6, 2011

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! this snippet helped me get my nested templates with jQuery UI tabs working, since they need the index in the div id. You the man.

@revbones-dev
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome! The lack of $index was one of my chief frustrations with this library! Especially after the MS AJAX Library (that got scrubbed for this turd) was so comparatively robust.

@fcsonline
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that is a good improvement but could be better if you don't modify the original dataItem. Think about modify the newTmplItem:

return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem, index ) : null;

If you print your datasource after the template render, all items includes the $index attribute, and this modification provoke an error in other places in my application.

Please sign in to comment.