for object使用
1.为进入object中直接使用其中的属性
<div id="result"></div> <script id="theTmpl" type="text/x-jsrender">
<div>
{{:name}} lives in
{{for address}}
<b>{{>city}}</b>
{{/for}}
</div>
</script> <script>
var data = [
{
"name": "Pete",
"address": {
"city": "Seattle"
}
},
{
"name": "Heidi",
"address": {
"city": "Sidney"
}
}
]; var template = $.templates("#theTmpl"); var htmlOutput = template.render(data); $("#result").html(htmlOutput);
</script>
2.切入模版
<body> <script id="peopleTemplate" type="text/x-jsrender">
<div>
{{:name}} lives in {{for address tmpl="#addressTemplate" /}}<!--切入其他模版-->
</div>
</script> <script id="addressTemplate" type="text/x-jsrender">
<b>{{>city}}</b>
</script> <div id="result"></div> <script>
var people = [
{
"name": "Pete",
"address": {
"city": "Seattle"
}
},
{
"name": "Heidi",
"address": {
"city": "Sidney"
}
}
]; var html = $("#peopleTemplate").render(people); $("#result").html(html);
</script> </body>
2.for array的使用,为循环标签
<body> <div id="result"></div> <script id="theTmpl" type="text/x-jsrender">
<b>{{:title}}</b>
<ul>
{{for members}}
<li>{{:name}} lives in <b>{{:address.city}}</b></li>
{{/for}}
</ul>
</script> <script>
var data = {
"title": "The A team",
"members": [
{
"name": "Pete",
"address": {
"city": "Seattle"
}
},
{
"name": "Heidi",
"address": {
"city": "Sidney"
}
}
]
}; var template = $.templates("#theTmpl");
var htmlOutput = template.render(data);
$("#result").html(htmlOutput);
</script> </body>
3.for标签还支持else的判断
else:表示for中的没有值循环或者为空,则进入
{{for members}}
Name: {{:name}}
{{else}}
No members...
{{/for}}
Conditional blocks: — Render the block content of the {{for}} tag (or referenced template) if the object is defined and is not an empty array, otherwise render the {{else}} block (or template)
<body> <div id="result"></div> <script id="theTmpl" type="text/x-jsrender">
<b>{{:title}}</b>
<ul>
{{for members}}
<li><b>Name:</b> {{:name}}</li>
{{else}}
<li>No members!</li>
{{/for}}
</ul>
</script> <script>
var data = [
{
"title": "The A team",
"members": []
},
{
"title": "The B team",
"members": [
{
"name": "Pete"
}
]
}
]; var template = $.templates("#theTmpl"); var htmlOutput = template.render(data); $("#result").html(htmlOutput);
</script> </body>