js template模版引擎 为什么要用

疑问:为什么要用 js template 为什么要 模版呢,

以下应用场景可以使用模板引擎:
1、如果你有动态ajax请求数据并需要封装成视图展现给用户,想要提高自己的工作效率。
2、如果你是拼串族或者数组push族,迫切的希望改变现有的书写方式。一直拼JS代码多不易维护可读性差
3、如果你在页面布局中,存在共性模块和布局,你可以提取出公共模板,减少维护的数量。

4:还可以使用循环\判断等语句, 减少工作量



     </script>  
      
    <!-- 模板内容 -->  
    <textarea id="template" style="display:none">  
       <strong>{$T.name} : {$T.list_id}</strong>  
       <table>  
            <tr>  
          <th>编号</th>  
          <th>姓名</th>  
                        <th>年龄</th>  
          <th>邮箱</th>  
        </tr>  
        {#foreach $T.table as record}  
        <tr>  
          <td>{$T.record.id}</td>  
          <td>{$T.record.name}</td>  
                        <td>{$T.record.age}</td>  
          <td>{$T.record.mail}</td>  
        </tr>  
        {#/for}  
       </table>  
    </textarea>  
      
    <!-- 输出元素 -->  
    <div id="result1" ></div>  



上面代码中,先导入了jQuery.js,然后导入jtemplates.js。

接下来新建了一个data数据的json对象。

var data = {
     ......
};

然后在HTMl页面上增加一个 输出元素 和 一个模板元素:

最后在JS给输出元素 附加模板 和 数据。

这样,运行代码后,出现如下图所示界面。

用户列表 : 编号89757
编号   姓名  年龄  邮箱
1        Rain   22    cssrain@domain.com
2        皮特   24   cssrain@domain.com
3       卡卡   20    cssrain@domain.com
4       戏戏   26    cssrain@domain.com
5       一揪   25    cssrain@domain.com



三 , 加载模板

这次把模板放到一个单独的页面中,而不是直接写在页面里。

新建一个template.html,放入以下代码:
Js代码  收藏代码

    <strong>{$T.name} : {$T.list_id}</strong>  
    <table>  
        <tr>  
        <th>编号</th>  
        <th>姓名</th>  
                <th>年龄</th>  
        <th>邮箱</th>  
    </tr>  
    {#foreach $T.table as record}  
    <tr>  
        <td>{$T.record.id}</td>  
        <td>{$T.record.name}</td>  
                <td>{$T.record.age}</td>  
        <td>{$T.record.mail}</td>  
    </tr>  
    {#/for}  
    </table>  


然后新建一个json文件,名称为cs.json,代码如下:
Js代码  收藏代码

    {  
    name: "用户列表",  
    list_id: "编号89757",  
        table: [  
         {id: 1, name: 'Rain', age: 22, mail: 'cssrain@domain.com'},  
         {id: 2, name: '皮特', age: 24, mail: 'cssrain@domain.com'},  
         {id: 3, name: '卡卡', age: 20, mail: 'cssrain@domain.com'},  
         {id: 4, name: '戏戏', age: 26, mail: 'cssrain@domain.com'},  
         {id: 5, name: '一揪', age: 25, mail: 'cssrain@domain.com'}  
    ]  
    }  


在jQuery中,可以通过$.ajax()方法来加载 json文件,代码如下:


    <script type="text/javascript">  
    $(function(){  
    $.ajax({  
       type:       "post",  
       dataType:   "json",  
       url:        "cs.json",  
    success:    function(data){  
                        .....  
                    }  
    });  
    });  
    </script>  


在success回调函数里,首先需要设置模板,然后需要添加数据。如下代码所示:


    success:    function(data){  
      
                        // 设置模板  
                       $("#result1").setTemplateURL("template.html?date="+(+new Date()), null, {filter_data: true});  
                        //   加载数据  
                        $("#result1").processTemplate(data);  
                    }  
    }  


完整代码如下所示:

    $(function(){  
    $.ajax({  
       type:       "post",  
       dataType:   "json",  
       url:        "cs.json",  
    success:    function(data){  
                        $("#result1").setTemplateURL("template.html?date="+(+new Date()), null, {filter_data: true});  
                        $("#result1").processTemplate(data);  
                    }  
    });  
    });


   jTemplates包含三个预定全局变量,分别是$T、$P、$Q。$T为模板提供数据调用功能,$P为模板提供参数变量调用功能,$Q.version提供当前jTemplate的版本

  jTemplates还支持#if、#for、#cycle、#foreach、#include、#param标签,帮助你处理实现复杂的业务情形。

{#if |COND|}..{#elseif |COND|}..{#else}..{#/if}
#if 示例:
{#if $T.hello} hello world. {#/if}
{#if 2*8==16} good {#else} fail {#/if}
{#if $T.age>=18)} 成人了 {#else} 未成年 {#/if}
{#if $T.list_id == 3} System list {#elseif $T.list_id == 4} Users List {#elseif $T.list_id == 5} Errors list {#/if}

{#for |VAR| = |CODE| to |CODE| [step=|CODE|]}..{#else}..{#/for}
或
{#for |variable| = |start| to |end| [step=|stepBy|]}..{#else}..{#/for}
#for 示例:
默认步长:{#for index = 1 to 10} {$T.index} {#/for} 
正向步长:{#for index = 1 to 10 step=3} {$T.index} {#/for}
负向步长及空循环:{#for index = 1 to 10 step=-3} {$T.index} {#else} nothing {#/for}
也可以在循环中使用变量:{#for index = $T.start to $T.end step=$T.step} {$T.index} {#/for}
说明:{#else}是在{#for...}未能执行的时的输出内容。


{#foreach |VAR| as |NAME| [begin=|CODE|] [count=|CODE|] [step=|CODE|]}..{#else}..{#/for}
#foreach 示例:
默认:{#foreach $T.table as record} {$T.record.name} {#/for}
指定起始位置:{#foreach $T.table as record begin=1} {$T.record.name} {#/for}
指定起始和循环次数:{#foreach $T.table as record begin=1 count=2} {$T.record.name} {#/for}
指定步长:{#foreach $T.table as record step=2} {$T.record.name} {#/for}
#foreach 内定环境变量:
$index - index of element in table
$iteration - id of iteration (next number begin from 0)
$first - is first iteration?
$last - is last iteration?
$total - total number of iterations
$key - key in object (name of element) (0.6.0+)
$typeof - type of element (0.6.0+)
#foreach 示例所需要的数据:
var data = {
name: 'User list',
list_id: 4,
table: [
{id: 1, name: 'Anne', age: 22, mail: 'anne@domain.com'},
{id: 2, name: 'Amelie', age: 24, mail: 'amelie@domain.com'},
{id: 3, name: 'Polly', age: 18, mail: 'polly@domain.com'},
{id: 4, name: 'Alice', age: 26, mail: 'alice@domain.com'},
{id: 5, name: 'Martha', age: 25, mail: 'martha@domain.com'}
]
};
(0.7.0+)版以后新增的功能,支持待循环集合用函数代替:
{#foreach |FUNC| as |NAME| [begin=|CODE|] [end=|CODE|] [count=|CODE|] [step=|CODE|]}..{#else}..{#/for}
例:
f = function(step) {
if(step > 100) return null; // stop if loop is too long
return "Step " + step;
};

$("#result").setTemplate("{#foreach f as funcValue begin=10 end=20} {$T.funcValue}<br/> {#/for}");
$("#result").processTemplate();
#foreach在每次循环时请求的就是f函数,然后传递参数给f使用,并返回结果给funcValue变量

#cycle 语法

{#include |NAME| [root=|VAR|]}
功能:提供子模板调用
示例:
{#template MAIN}
{* this is comment *}
{$T} {* $T == $T.toSource() *}
<table>
{#foreach $T.table as record}
{#include ROW root=$T.record}
{#/for}
</table>
{#/template MAIN}

{#template ROW}
<tr class="values=['bcEEC','bcCEE']} {#cycle">
<td>{$T.name}</td>
<td>{$T.mail}</td>
</tr>
{#/template ROW}
说明:{#template MAIN} 是指定模板的主要部分,必不可少。
{#template ROW}是定义一个名为“ROW”的子模板。
{#include ROW root=$T.record}是主模板调用“ROW”子模板,并传递参数$T.record


{#param name=|NAME| value=|CODE|}
功能:定义模板内的局部变量参数,使用$P调用。
示例:
$("#result").setTemplate("{#param name=x value=888}{$P.x}");
$("#result").processTemplate();
输出结果:888
示例:
$("#result").setTemplate("{#param name=x value=$P.x+1}{$P.x}");
$("#result").setParam('x', 777);
$("#result").processTemplate();
输出结果:778
示例:
$("#result").setTemplate("<ul>{#foreach $T.table as row}<li>{$P.x} {$T.row.name}</li>{#param name=x value=$P.x+3}{#/for}<ul>");
$("#result").setParam('x', 1);
$("#result").processTemplate(data);
需要数据:
var data = {
name: 'User list',
list_id: 4,
table: [
{id: 1, name: 'Anne', age: 22, mail: 'anne@domain.com'},
{id: 2, name: 'Amelie', age: 24, mail: 'amelie@domain.com'},
{id: 3, name: 'Polly', age: 18, mail: 'polly@domain.com'},
{id: 4, name: 'Alice', age: 26, mail: 'alice@domain.com'},
{id: 5, name: 'Martha', age: 25, mail: 'martha@domain.com'}
]
};
输出结果:
# 1 Anne
# 4 Amelia
# 7 Polly
# 10 Alice
# 13 Martha



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值