<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<meta charset="utf-8"/>
<script src="./frame/jquery/jquery-1.11.0.min.js"></script>
<script src="./frame/jquery/jquery-jtemplates.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
//初始化JSON数据
var data = {
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'}
]
};
// 附上模板
$("#result1").setTemplateElement("template");
// 给模板加载数据
$("#result1").processTemplate(data);
});
</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 style="background-color: {#cycle values=['rgb(133, 227, 224)','rgb(204, 237, 236)']}">
<td>{$T.record.id}</td>
<td>{$T.record.name}</td>
<td>{$T.record.age}</td>
<td>{$T.record.mail}</td>
</tr>
{#/for}
</table>
{#for index = 1 to 10} {$T.index}{$T.name.link('http://www.baidu.com')} {#/for}
</textarea>
<!-- 输出元素 -->
<div id="result1" ></div>
</body>
</html>
jTemplates的工作方式:1、setTemplate 指定可处理的模版对象 2、processTemplate 对模版化的对象进行数据处理
语法分析:
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 longreturn "Step " + step;
};
$("#result").setTemplate("{#foreach f as funcValue begin=10 end=20} {$T.funcValue}<br/> {#/for}");
$("#result").processTemplate();
#foreach在每次循环时请求的就是f函数,然后传递参数给f使用,并返回结果给funcValue变量
{#cycle values=|ARRAY|}
功能:提供周期性的调用,在循环中实现交替样式功能时可用到
示例:
{#cycle values=[1,2,3,4]}
下面模板在执行循环时,就会周期性的调用#cycle数组中的值,这样就能实现行交替的效果:<table width=\"200\">
{#foreach $T.table as row}
<tr bgcolor=\"{#cycle values=['#AAAAAA','#CCCCCC']}\">
<td>{$T.row.name.link('mailto:'+$T.row.mail)}</td>
</tr>
{#/for}
</table>
{#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
一、简单Demo:
1.下载 jTemplates 和 jQuery:
jTemplates.0.8.4:http://jtemplates.tpython.com/jTemplates_0_8_4.zip jQuery:https://jquery.com/download/
2.安装:
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery-jtemplates.js"></script>
3.示例:
<script type="text/javascript" >
var mydata = { name: "ziry", age: "18" };
$("#show").setTemplateElement( "templates" );
$("#show").processTemplate(mydata);
</script>
<!-- 生成输入内容 -->
<div id="show">
</div>
<!-- 这里是模版的内容 -->
<textarea id="templates" style="display:none">
<p>{$T.name}<p>
</textarea>
4.输出:
<div id="show"> <p>ziry<p> </div>
5.详解:
在{…}可以是任何JavaScript代码。有三个预定义的变量:
- $T - (data)提供数据调用功能
- $P - (parameters)提供参数变量调用功能
- $Q - XHTML元素的属性(XHTML element's attributes),$Q.version提供当前jTemplate的版本
注:数据和参数应该是有效的JavaScript对象。
var mydata = { name: 'ziry', age: '18' };
{$T.name} 输出:ziry
{2*3} 输出:6
二、标签:
1.#if 语法
{#if |COND|}
...
{#elseif |COND|}
...
{#else}
...
{#/if}
示例:
{#if $T.age>=18}
成人了
{#else}
未成年
{#/if}
2.#for 语法:
{#for |VAR| = |CODE| to |CODE| [step=|CODE|]}
...
{#else}
...
{#/for}
或
{#for |variable| = |start| to |end| [step=|stepBy|]}
...
{#else}
...
{#/for}
示例:
● 默认步长:
{#for index = 1 to 10}
{$T.index}
{#/for}
输出:1 2 3 4 5 6 7 8 9 10
● 正向步长:
{#for index = 1 to 10 step=2}
{$T.index}
{#/for}
输出:1 3 5 7 9
● 负向步长
{#for index = -1 to -10 step=-2}
{$T.index}
{#/for}
输出:-1 -3 -5 -7 -9
● 空循环
{#for index = 1 to 10 step=-1}
{$T.index}
{#else}
nothing
{#/for}
输出:nothing
说明:{#else}是在{#for...}未能执行的时的输出内容。
也可以在循环中使用变量:
{#for index = $T.start to $T.end step=$T.step}
{$T.index}
{#/for}
3.#foreach 语法:
{#foreach |VAR| as |NAME| [begin=|CODE|] [count=|CODE|] [step=|CODE|]}
...
{#else}
...
{#/for}
示例:
所需要的数据:
var data = {
name: 'userList',
list_id: 4,
table: [
{id: 1, name: 'ziry', age: 22},
{id: 2, name: 'lee', age: 24},
{id: 2, name: 'aaa', age: 24}
]
};
● 默认:
{#foreach $T.table as u}
{$T.u.name}
{#/for}
输出:ziryleeaaa
● 指定起始位置:
{#foreach $T.table as u begin=1}
{$T.u.name}
{#/for}
输出:leeaaa
● 指定起始和循环次数:
{#foreach $T.table as u begin=1 count=2}
{$T.u.name}
{#/for}
输出:leeaaa
● 指定步长:
{#foreach $T.table as u step=2}
{$T.u.name}
{#/for}
输出:ziryaaa
#foreach 内定环境变量:
-
$index - index of element in table(迭代索引,从0开始)
-
$iteration - id of iteration (迭代ID,从0开始)
-
$total - total number of iterations(迭代次数,从1开始)
-
$typeof - type of element (0.6.0+)(得到数据类型:number,string,object...)
示例:
{#foreach $T as i count=3}
{$T.i$index+1}: {typeof $T.i},
{#/for}
输出:1: number,2: string,3: object,
-
$first - is first iteration(是否是第一个)?
-
$last - is last iteration(是否是最后一个)?
示例:
{#for index = $T.start to $T.end}
{$T.content}{$T.index}
{#if !($T.index$last)} , {#/if}
{#/for}
输出:ID:2, ID:3, ID:4, ID:5
-
$key - key in object (name of element) (0.6.0+) (键值Key)
示例:
{#foreach $T as i}
{$T.i$key}:{$T.i},
{#/for}
输出:a:1,b:2,c:3,
-
(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;
};
{#foreach f as funcValue begin=10 end=20}
{$T.funcValue}<br/>
{#/for}
#foreach在每次循环时请求的就是f函数,然后传递参数给f使用,并返回结果给funcValue变量
4.#cycle 语法:
{#cycle values=|ARRAY|}
功能:提供周期性的调用,在循环中实现交替样式功能时可用到
示例:
{#cycle values=[1,2,3,4]}
下面模板在执行循环时,就会周期性的调用#cycle数组中的值,这样就能实现行交替的效果:
<table width=\"200\">
{#foreach $T.table as row}
<tr bgcolor=\"{#cycle values=['#AAAAAA','#CCCCCC']}\">
<td>{$T.row.name.link('mailto:'+$T.row.mail)}</td>
</tr>
{#/for}
</table>
5.#include 语法:
{#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
6.#param 语法:
{#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);
7. #literal 语法
{#literal}..{#/literal}
在模板中禁用转义
示例:
{#literal}class Car {<br/> int fuel;<br/>};{#/literal}
输出:
class Car {
int fuel;
};
8. {*...*} 注释
没什么好说的,就是注释
9. 可直接调用JS方法
function inc(number) {
return number + 1;
};
$("#result").setTemplate("{$P.inc(4)}");
$("#result").setParam('inc', inc);
$("#result").processTemplate();
输出:5
三、JTemplates方法
1. 指定模板执行HTML元素
jQuery jQuery.fn.setTemplate(String template, Array includes, Object settings); jQuery jQuery.fn.setTemplate(Template template);
2.从url下载模板,并将其分配给HTML元素
jQuery jQuery.fn.setTemplateURL(String url, [Array includes], [Object settings]);
3.使用HTML元素“elementName”(textarea)的内容作为模板,并将其分配给HTML元素(0.6.5+)
jQuery jQuery.fn.setTemplateElement(String elementName, [Array includes], [Object settings]);
4.创建并返回模板
Template jQuery.createTemplate(String template, [Array includes], [Object settings]); Template jQuery.createTemplateURL(String url, [Array includes], [Object settings]); Template jQuery.getTemplate(Element element); string jQuery.processTemplateToText(Template template, [Object data], [Object parameter]);
5.创建并返回已指定的元素的模板数量,这些元素已经指定了任何模板。
Number jQuery.fn.hasTemplate();
6.移除模版
jQuery jQuery.fn.removeTemplate();
7.设置参数
jQuery jQuery.fn.setParam(String name, Object value);
8.运行模板引擎,生成结果并将其分配给HTML元素
jQuery jQuery.fn.processTemplate(Object data, [Object parameters]); jQuery jQuery.fn.processTemplateURL(String url, [Object parameters], [Object options]);
9.实时刷新模版
Updater jQuery.fn.processTemplateStart(String url, Array param, Integer interval, [Array args], [Object options]); jQuery jQuery.fn.processTemplateStop();
10.启用/禁用调试模式(全局变量。错误可用于所有模板的错误。默认值:false()。对于终端用户来说,可以通过禁用来避免大多数错误。启用它有助于发现任何模板问题。)
jQuery.jTemplatesDebugMode(Boolean value);
Settings 参数:
-
disallow_functions:
禁止在数据$T缺省情况下使用函数:false,依赖于:clone_data,clone_params -
filter_data:
替换chars:<,>,&,',",在数据$T到HTML实体的,默认值:true,依赖于:clone_data -
filter_params:
替换chars:<,>,&,',",在参数$P到HTML实体,默认:false,依赖于:clone_params -
runnable_functions:
自动运行函数function (from data) inside {} ("runnable function"),默认为:false(0.6.0+) -
clone_data:
克隆输入数据,默认值:true(0.7.0+) -
clone_params:
克隆输入参数,默认值:true(0.7.0+) -
f_cloneData:
使用数据克隆的功能:TemplateUtils.cloneData -
f_escapeString:
用于转义字符串的函数默认:TemplateUtils.escapeHTML -
f_parseJSON:
用于解析JSON,默认值的使用函数是jQuery.parseJSON(data)或TemplateUtils.parseJSON(data), //集合数据不能有函数
示例:
$("#result").setTemplate("Bold: {$T}", null, {filter_data: true});
$("#result").processTemplate("<b>bold</b>");
参考官网API:
参考博客:
