handlebars模板引擎 集成到jquery

@admin  April 18, 2018
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>templateStudy</title> 
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/handlebars.js/4.0.11/handlebars.min.js"></script>

    <script id="stuTempId" type="text/x-handlebars-template">
        <section>
            <ul>
                {{#each stu}}
                    <li>{{@index}}:{{@key}}:{{this}}</li>
                {{/each}}
            </ul>
        </section>
        <table border="1px">
            <tr><td>序号</td><td>学号</td><td>姓名</td><td>年龄</td><td>序号</td><td>姓名</td><td>年龄</td></tr>
            {{#each stus}}
                <tr>
                    <td>{{@index}}</td>
                    <td>{{id}}</td>
                    <td>{{name}}</td>
                    <td>{{#if age}}{{age}}{{else}}未填写{{/if}}</td>
                    <td>{{@key}}</td>
                    <td>{{this.name}}</td>
                    <td>{{#with this}}{{age}}{{/with}}</td>
                </tr>
            {{/each}}
        </table>
    </script>
    <script type="text/javascript">
    (function($){
        var compiled = {};
        $.fn.template = function(data){
            var template = $.trim($(this).first().html());
            if(compiled[template] == undefined){
                compiled[template]=Handlebars.compile(template);
            }
            return $(compiled[template](data));
        };
    })(jQuery)
        $(function () {
            var data={
                stus:[
                    {id:100,name:"apple1",age:11},
                    {id:200,name:"apple2"},
                    {id:300,name:"apple3",age:33},
                ],
                stu:{id:300,name:"apple3",age:33}
            };
            $("#stuInfoId").empty().append($("#stuTempId").template(data).filter("*"));  //filter("*")用于匹配所有html节点,过滤掉文本节点
        });
    </script>
</head>
<body>
    <section id="stuInfoId"></section>
</body>
</html>

评论已关闭