artTemplate模板渲染页面

artTemplate模板来构造页面,优点在哪里呢,首先,页面易读性更高了,其次使得其性能无论在前端还是后端都有极其出色的表现。故此分享一下,还请大神们多多指点。

//首先来个html盒子,来装数据模板
 <div id="container"></div>

点击下载:artTemplate.js

<script type="text/javascript" src="template.js"></script>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>

JavaScript渲染模板

<script id="demo" type="text/html">
{{if isAdmin}}
    <div id="nav">
        <div class="menu-main">
        //一级导航
            {{each list as value i}}
                <li class="nav-menu"><a href="javascript:void(0);">{{i}}</a></li>
            {{/each}}
        </div>
    </div>
    //二级导航渲染
    <div class="sub-nav">
        {{each list as value i}}
            <ul class="sub-nav-items">
                {{each list[i] as value j}}
                    <li class="nav-item"><a href="javascript:void(0);">{{j}}</a></li>
                {{/each}}
            </ul>
        {{/each}}
    </div>
    <div class="filter-content">
    //三级导航渲染
        <div class="filter-section">
            {{each list as value i}}
                {{each list[i] as value j}}
                    <div class="filter-list">
                    {{each list[i][j] as value k}}
                        <a href="javascript:void(0);" class="filter-sel">{{value}};</a>
                    {{/each}}
                    </div>
                {{/each}}
            {{/each}}
        </div>
    </div>
{{/if}}
</script>

javascript渲染根据json数据渲染到模板中去

var data = {
    isAdmin: true,
    list : {
        "电视" : {
            "大陆剧" : ["好大一个家","平凡的世界","收获的季节","刘老根","乡村爱情","士兵突击","神探狄仁杰","武媚娘传奇"],
            "美剧" : ["吸血鬼日记","闪电侠","行尸走肉","童话镇","破产姐妹","格林"],
            "台剧" : ["有爱一家人","再见阿郎","我的宝贝四千金","新白娘子传奇"],
            "韩剧" : ["来自星星的你","匹诺曹","奔跑吧玫瑰","美女的诞生","未来的选择",],
        },
        "电影" : {
            "动作" : ["A计划","警察故事","黄飞鸿","特务迷城","卧虎藏龙","逗你玩"],
            "爱情" : ["保定爱情","山楂树之恋","北京遇上西雅图"],
            "恐怖" : ["僵尸家族","驱鬼警察","僵尸道长"]
        },
        "综艺" : {
            "百变大咖秀" : ["第一期","第二期","第二期","第四期"],
            "快乐大本营" : ["谢娜","何炅","维嘉","杜海涛","吴昕"],
            "天天向上" : ["汪涵","欧弟","田园","钱枫","小五"],
            "康熙来了" : ["小S","蔡康永","赵薇","萧敬腾","阿雅","吴宗宪"]
        }
    }
}
var html = template('demo', data);
document.getElementById('container').innerHTML = html;

例子效果

发表评论

电子邮件地址不会被公开。 必填项已用*标注