首页 > 代码库 > javascript模板库jsrender for循环嵌套示例

javascript模板库jsrender for循环嵌套示例

最近在参与整合前端的框架,我们知道javascript最强大的模板引擎之一当属jsrender,号称下一代jquery模板引擎的标准实现。

通常在模板merge的过程中,我们会遇到两次乃至三级嵌套的情形,强大的jsrender自然会支持,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="http://www.mamicode.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="http://www.mamicode.com/jsrender.js"></script>
    <title>jsrender nest demo</title>
</head>
<body>
<div id="studentList">abc</div>
<script type="text/x-jsrender" id="studentTemplate">
    {{for #data}}
        <h3>{{:name}}</h3>
        <ul>
        {{for language}}
            <li>
            {{:#parent.parent.data.name}} is learning {{:title}}<br/>
            {{for scores}}
                <a href="http://www.mamicode.com/#">{{:score}}</a>
            {{/for}}
            </li>
        {{/for}}
        </ul>
    {{/for}}
</script>
<script type="text/javascript">
    var students = [{name:"张三",language:[{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"英",scores:[{score:12},{score:13},{score:14}]},{title:"数",scores:[{score:12},{score:13},{score:14}]}]},
                    {name:"李四",language:[{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"中",scores:[{score:12},{score:13},{score:14}]}]},
                    {name:"王五",language:[{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"中",scores:[{score:12},{score:13},{score:14}]},{title:"中",scores:[{score:12},{score:13},{score:14}]}]}];
    $("#studentList").html($("#studentTemplate").render(students));
</script>
</body>
</html>

效果如下:

技术分享

 

javascript模板库jsrender for循环嵌套示例