Reputation: 18049
Ok this is a little like inception for json objects and jquery templating... I want to know how to go deeper. The problem is that i am lazy and want the code to do the work for me....
Q:> How do you call a jQuery template recursively.
Take this json object:
var Links =
[{"Name":"Home","NiceUrl":"/home/","Children":null},
{"Name":"MX-8","NiceUrl":"/mx-8/","Children":null},
{"Name":"Quiz","NiceUrl":"/quiz/","Children":
[{"Name":"Thank you","NiceUrl":"/quiz/thank-you/","Children":
[{"Name":"Can't get here","NiceUrl":"/URL/","Children":null}]
}]
}];
I can easily get to "Quiz" and its child "Thankyou" using the following template:
<script id="itemTemplate" type="text/x-jquery-tmpl">
<li><a href="${NiceUrl}">${Name}</a>
{{tmpl($data) "#childTemplate"}}
</li>
</script>
<script id="childTemplate" type="text/html">
<ul>{{each Children}}<li><a href="${NiceUrl}">${Name}</a></li>{{/each}}</ul>
</script>
also used is the html and the call to replace it:
<script type="text/javascript">
$("#itemTemplate").tmpl(Links).appendTo("#SiteMapHolder");
</script>
<ul id="SiteMapHolder">
<%--jQuery Template will replace this empty space--%>
</ul>
I have tried setting the type of the second template to "text/x-jquery-tmpl" and calling a 3rd template but the data being passed seems to be the same as the parent that is calling it.
so to all beings of higher intelligence and experience then i, show me the way to be lazy and call a jQuery template recursively?
PS:sorry this is not in jsFiddle. it doesn't like my script tags. :(
Upvotes: 2
Views: 1622
Reputation: 6567
I think you just need to check if Children exists and make a recursive call to the same item template with the Children as the data. You would conditionally also add the ul tag. See this jsfiddle for what I mean: http://jsfiddle.net/bernardchen1/SK2c6/.
The template itself that I used looks like this:
<script id="itemTemplate" type="text/x-jquery-tmpl">
<li><a href="${NiceUrl}">${Name}</a>
{{if Children}}
<ul>
{{tmpl(Children) "#itemTemplate"}}
</ul>
{{/if}}
</li>
Upvotes: 3