Javascript 模板引擎(Juicer.js)--实现数据和视图模型的分离

  • 544 浏览
  • 最后发表 2018-10-31 08:23
Gavin liu 发布于 2018-10-31 08:23

 

    在开发流程表单或自定义页面时,经常会遇到类似主从表数据的展示,简单的做法就是循环的去拼接html,简单结构时这样做没问题。复杂的结构就不是很合适。

Juicer.js可以方便的把数据和模板分离。

具体使用如下:

1、引入Juicer

<script type="text/javascript" src="juicer-min.js"></script>

2、定义Javascript模板,如:

<script type="text/template" id="contract_template">

        <tr rel="OtherMainContract" index="${index}">

            <th style="width:150px;">对方签约主体${index|toUpperNum,index}:</th>

            <td style="width:720px;"colspan="3">

                <input type="text" name="OtherMainContract" class="txtNormal" validate="{ required: true, tips: '请填写对方签约主体'}" style="width: 90%"  maxlength="290"/>

                {@if index==0}

                <span rel="OtherMainContractActive"><img src="../../../themes/brown/icon_11.jpg" alt="添加" width="14px" height="14px" onclick="AddOtherMainContract()" style=" cursor:pointer;"/></span>

                {@else}

                <span rel="OtherMainContractActive"><img src="../../../themes/brown/icon_10.jpg" alt="删除" width="14px" height="14px" onclick="DeleteOtherMainContract('${index}')" style=" cursor:pointer;"/></span>

                {@/if}

                <input type="hidden" name="OtherMainContractId" />

            </td>

        </tr>

    </script>

 

3、使用模板

如上的模板较复杂时,如果采用拼接html的方法,不管格式还是数据绑定时都不是很方便。

具体使用,如下:

   a、获取模板:

   var tpl = $("#contract_template").html();

   b、数据绑定:

   var data = { "index": index };

   $("#OtherMainContract>tbody").append(compiled_tpl.render(data));

   c、如果模板中有事件时,需要注册事件:

   juicer.register('toUpperNum', toUpperNum);

简单使用如上,更多及详细使用操作,其他同事可做补充。

  • 喜欢
  • steve.shi

要回复问题请先登录注册

Close