
Question:
I'm creating a jQuery Template system that recursively calls the same template as needed. Most of the examples of "recursive" templates are actually just templates calling other templates, even the ones that <a href="https://stackoverflow.com/questions/5263036/jquery-nested-templates-using-options-parameter/5263407#5263407" rel="nofollow">pass around the $item
object to retain custom functions</a>. In this case, I want to call the same template with a sub-portion of the original $data
(AKA $item.data
) while also passing around custom template functions passed in to the options of the original tmpl
call.
// original template call
$("#someTemplate").tmpl(data, {
someFunction1: function(itemToCheck) {
return itemToCheck.p3;
},
someFunction2: function(itemToCheck) {
return itemToCheck.p1 + ", " + itemToCheck.p2;
}
}).appendTo(".results");
<!--in-template secondary call-->
{{tmpl($data.sub, $item) "#someTemplate"}}
<a href="http://jsfiddle.net/patridge/YBFqR/" rel="nofollow">Full code jsFiddle</a>
It seems that passing around $item
as the options parameter for the recursive call results in the data parameter being ignored, probably because $item.data
contains the original object and it simply overwrites the new data parameter. As a result, at each recursive level, I am still operating at the original caller level in the object and making no further progress in the object structure (hence the stack issue).
Is there some other property of $item
I need to use to pass around only the custom functions without having $item.data
override the template data being passed in?
You definitely cannot just pass $item
as the options parameter to {{tmpl}}
. After <a href="https://github.com/jquery/jquery-tmpl/blob/master/jquery.tmpl.js#L30" rel="nofollow">looking at the code</a>, it sets data
for the new template call and then blows it away with the original $item.data
through jQuery.extend
a few lines later.
While I cannot seem to find a variable on $item
that wraps all the custom functions, I was able to work around this issue by passing in each custom function individually from the original $item
object. Not ideal, but it works.
{{tmpl($data.sub, { someFunction1: $item.someFunction1, someFunction2: $item.someFunction2 }) "#someTemplate"}}