too much recursion using jquery templates
I'm trying to render a recursive template, but I'm getting a "too much recursion" error...
Can anyone tell what I'm doing wrong here?: code in jsfiddle
Thanks!
EDIT 1 (code added to post):
The HTML
<script id="my_template" type="text/j-query-tmpl">
<ul class="modules_ul">
{{each(i, module) modules}}
<li>${module.mod_name}</li>
{{if module.sub_modules}}
{{tmpl "my_template_compiled"}}
{{/if}}
{{/each}}
</ul>
</script>
The JS
var data = {"modules":[
{
"id_modules": "1",
"id_modules_parent": "0",
"mod_name": "mod 1",
"开发者_JS百科sub_modules": [
{
"id_modules": "5",
"id_modules_parent": "1",
"mod_name": "mod 1a"
},
{
"id_modules": "7",
"id_modules_parent": "1",
"mod_name": "mod 1b"
}
]
},
{
"id_modules": "2",
"id_modules_parent": "0",
"mod_name": "mod 2",
"sub_modules": [
{
"id_modules": "6",
"id_modules_parent": "2",
"mod_name": "mod 2a",
"sub_modules": [
{
"id_modules": "3",
"id_modules_parent": "6",
"mod_name": "mod 2aa"
}
]
},
{
"id_modules": "4",
"id_modules_parent": "2",
"mod_name": "mod 2b"
}
]
}
]};
$("#my_template").template("my_template_compiled");
$.tmpl("my_template_compiled", data).appendTo("#some_div");
http://jsfiddle.net/aNPvz/22/ (Don't ask me why the bullet points don't render on the jsFiddle; they do when I build my own page.)
{{tmpl "my_template_compiled"}}
was calling the entire modules instead of just the sub-modules. Note the change to your json structure to make recursion possible.
<html>
<head>
<style></style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script id="my_template" type="text/j-query-tmpl">
<ul class="modules_ul">
{{each(i, module) modules}}
<li>${module.mod_name}</li>
{{if module.sub}}
{{tmpl(module.sub) "my_template_compiled"}}
{{/if}}
{{/each}}
</ul>
</script>
<script>
$(function() {
$("#my_template").template("my_template_compiled");
$.tmpl("my_template_compiled", data).appendTo("#some_div");
});
var data = {"modules":[
{
"id_modules": "1",
"id_modules_parent": "0",
"mod_name": "mod 1",
"sub":{"modules": [
{
"id_modules": "5",
"id_modules_parent": "1",
"mod_name": "mod 1a"
},
{
"id_modules": "7",
"id_modules_parent": "1",
"mod_name": "mod 1b"
}
]}
},
{
"id_modules": "2",
"id_modules_parent": "0",
"mod_name": "mod 2",
"sub":{"modules": [
{
"id_modules": "6",
"id_modules_parent": "2",
"mod_name": "mod 2a",
"sub":{"modules": [
{
"id_modules": "3",
"id_modules_parent": "6",
"mod_name": "mod 2aa"
}
]}
},
{
"id_modules": "4",
"id_modules_parent": "2",
"mod_name": "mod 2b"
}
]}
}
]};
</script>
</head>
<body>
<div id="some_div"></div>
</body>
</html>
精彩评论