handlebars获取json数据(集合中的元素存在属性是一个集合或者数组)each嵌套也可使用with语法

    @RequestMapping("testDemo04.do")
    public List<Emp> testDemo04(){
        List<Emp> emps = new ArrayList<Emp>();
        Emp emp1 = new Emp(1111, "老龚", 33, "1", 1000.00, new Date(), new Timestamp(System.currentTimeMillis()));
        Emp emp2 = new Emp(1111, "老李", 30, "0", 1600.00, new Date(), new Timestamp(System.currentTimeMillis()));

        emp1.setJobs(new String[]{"销售副经理","开发工程师","测试工程师"});
        emp2.setJobs(new String[]{"开发工程师","测试工程师"});

        emps.add(emp1);
        emps.add(emp2);

        return emps;
    }
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width="50%" border="1">
    <thead>
        <tr>
            <th>NO.</th>
            <th>ID</th>
            <th>NAME</th>
            <th>AGE</th>
            <th>GENDER</th>
            <th>SALARY</th>
            <th>BIRTHDAY</th>
            <th>HIREDATE</th>
            <th>JOBS</th>
        </tr>
    </thead>
    <tbody id="demo">

    </tbody>
</table>



<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/handlebars-4.0.10.min.js"></script>

<!-- 定义handlebars模板 -->
<script type="text/x-handlebars-template" id="demo_ht">
    {{#each this}}
        <tr>
            <td>{{myCount @index}}</td>
            <td>{{id}}</td>
            <td>{{name}}</td>
            <td>{{gender}}</td>
            <td>{{age}}</td>
            <td>{{salary}}</td>
            <td>{{birthday}}</td>
            <td>{{hiredate}}</td>
            <td>
                {{#each jobs}}
                    {{this}}
                {{/each}}
            </td>
        </tr>
    {{/each}}
</script>
    <!-- 使用with也可以
        {{#with jobs}}
            {{#each this}}
                {{this}}
            {{/each}}
        {{/with}}
     -->
<script type="text/javascript">
    $(function(){
        $.ajax({
            type:"post",
            url:"test/testDemo04.do",
            dataType:"json",
            success:function(data){
                //编译模板
                var demo_ht = Handlebars.compile($("#demo_ht").html());

                //定义一个helper 实现在index基础上从1开始
                Handlebars.registerHelper("myCount" , function(index){
                    return index + 1 ;
                });

                //模板渲染数据
                var _html = demo_ht(data);
                //dom操作
                $("#demo").html(_html);
            },
            error:function(){
                alert("请求发生异常!");
            }
        });
    });
</script>
</body>
</html>

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值