handlebars(registerHelper传多个值)处理

2018-09-18  本文已影响132人  唐人不自醉

正常情况下从后台请求过来数据之后都是一个字段对应页面一个位置渲染(一个萝卜一个坑),有时候就给你两个萝卜,让你计算萝卜和萝卜之间的差值进行页面渲染,今天说关于萝卜的事情~。

整个页面代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板的value传递多个值</title>
    <style>
        table, th, td {
            border: 1px solid red;
            text-align: center;
        }
    </style>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>与上一次成绩比较</th>
    </tr>
    </thead>
    <tbody class="student-temp">
    <script type="text/x-handlebars-template" id="student-temp">
        {{#each student}}
        <tr>
            <td>{{name}}</td>
            <td>{{age}}</td>
            <td>{{gender}}</td>
            <td>{{#fractionData fraction fractions}}{{/fractionData}}</td>
        </tr>
        {{/each}}
    </script>
    </tbody>
</table>
<script type="text/javascript" src="../jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="../handlebars-v4.0.10.js"></script>
<script>
    //    模拟数据
    var data = {
        "student": [
            {
                "name": "柳1",
                "age": '3',
                "gender": '女',
                "fraction": '34',
                "fractions": '54',
            },
            {
                "name": "柳2",
                "age": '3',
                "gender": '女',
                "fraction": '74',
                "fractions": '84',
            },
            {
                "name": "柳3",
                "age": '3',
                "gender": '女',
                "fraction": '34',
                "fractions": '84',
            }
        ]
    };

    //    获取到handlebars这个模板中的全部html内容
    var studentTemp = $('#student-temp').html();
    //    编译
    var HanStudent = Handlebars.compile(studentTemp);


    Handlebars.registerHelper('fractionData',function (fraction,fractions) {
        console.log(fraction);
        console.log(fractions);
       return value=fractions-fraction
    });

    //把编译完成的代码放入到 .student-temp 的这个容器中
    $('.student-temp').html(HanStudent(data))

</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读