【转载】Asp.Net中使用基于jQuery的javascript前台模版引擎JTemplate

JTemplate是基于jQuery的开源的前端模版引擎,在Jtemplate模板中可以使用if判断、foreach循环、for循环等操作,使用Jtemplate模板优点在于ajax局部刷新界面时候不必要拼接html语句、可以通过ajax获取JSON格式的数据、在模版中允许使用javascript代码、允许你创建串接模版、允许你在模版中创建参数、即时刷新,自动从服务器端获取更新内容。

一、 jTemplate常用的标签有:

1、template 模版标签

2、if .. elseif .. else .. /if 条件语句

3、foreach .. else .. /for 循环

4、for .. else .. /for 循环

5、continue, break 继续或中断

二、jTemplates的语法:

(1)if语法

{#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}

(2)for语法

{#for |VAR| = |CODE| to |CODE| [step=|CODE|]}..{#else}..{#/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...}未能执行的时的输出内容。

(3)foreach语法

{#foreach |VAR| as |NAME| [begin=|CODE|] [count=|CODE|] [step=|CODE|]}..{#else}..{#/for}

示例:

默认:{#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}

三、Jtemplate模板使用方法如下:

<div ></div>  
    <textarea  >  
       <table>  
         <tr>  
           <th></th>  
          </tr>  
         {#foreach $T as record}  
         <tr>  
           <td>{$T.record.属性名}</td>  
         </tr>  
        {#/for}  
       </table>  
    </textarea>  

绑定数据以及调用语句中关键的2句:

$('#result').setTemplateElement('template_1');  //设置模版  
$('#result').processTemplate(data);   //执行数据