Reputation: 1418
No, this is not a repeat of this question... a little related though, so i will use the code from that Q for comparison.
I am attempting to get the index from within a nested template, using the {{tmpl}} tag. Using the tmlp tag is much like an {{each}} tag as in the question linked above, however the $index property is not present.
<script id="answerTable" type="text/x-jquery-tmpl">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
{{tmpl(answersObj) '#answers' }}
</table>
</script>
<script id="answers" type="text/x-jquery-tmpl">
<tr>
<th><input type="radio" name="group1" value="---!INDEX HERE!---" /></th>
<td>${AnswerText}</td>
</tr>
</script>
I dont want to wind up with a messy way to do this- i would prefer to modify the lib if possible. Anyone have any ideas where the current lib could be modified to support this feature - git hub source. This code is a little over my head, im short on time, and understanding this lib is not within my current projects scope ;)
Upvotes: 2
Views: 2493
Reputation: 1418
I have also learned of another technique that may or may not work for your scenario...
you can use jQuery.inArray to get the index from the parent data object - assuming youre keeping your parent data object in sync.
Upvotes: 0
Reputation: 1418
OK had to modify the template lib. see this link for github patch.
line 150-155 of original (current version) of jquery.tmpl.js
ret = jQuery.isArray( data ) ?
jQuery.map( data, function( dataItem ) {
return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
}) :
[ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
modified to support $index
ret = jQuery.isArray( data ) ?
jQuery.map( data, function( dataItem, index ) {
if(dataItem){dataItem.$index = index;}
return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
}) :
[ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
Upvotes: 3