jTemplates是一个功能丰富的模板引擎,它作为一个jQuery插件来执行。jTemplates支持很多先进的功能,包括:
外部模板--您可以通过提供的URL从外部文件加载模板,外部文件可以包含多个模板;
外部数据--您可以从外部URL加载数据;
实时刷新--你可以自动定期的更新模板内容;
HTML编码--你可以阻止诸如<和>的编码字符对JavaScript插入的攻击;
Includes--您可以在一个模板中包含另一个模板;
调试模式--您可以在出错的地方终止模板引擎,并显示错误信息。
下面示例中的代码演示了如何使用jTemplates显示产品清单。
<script src="../jquery-1.4.1.js" type="text/javascript"></script>
<script src="jquery-jtemplates_uncompressed.js" type="text/javascript"></script>
<script type="text/javascript">
var data = {
products: [
{ name: "Laptop", price: 788.67 },
{ name: "Comb", price: 2.50 },
{ name: "Pencil", price: 1.99 }
]};
$(showProducts);
function showProducts() {
// attach the template
$("#results").setTemplateElement("template");
// process the template
$("#results").processTemplate(data);
}
function formatPrice(price) {
return "{1}quot; + price;
}
}
</script>
setTemplateElement()方法给HTML元素指定一个模板,processTemplate()方法使用所提供的数据处理模板。
上面的代码中,加载的模板为名为textarea的元素,下面就是模板在页面主体中呈现的外观。
<textarea id="template" style="display:none">
{#foreach $T.products as product}
<div>
Product Name: {$T.product.name}
<br />
Product Price: {formatPrice($T.product.price)}
</div>
{#/for}
</textarea>
注意,一个jTe
默认情况下,为了防止JavaScript的插入攻击,在传递给模板的数据中,jTemplate 的HTML编码了包含的特殊字符。例如,如果一个产品的名称为<b>Laptop<b>,那么,名称将被转换成<b>Laptop</b> 。
jTemplates使您可以同时从外部URL加载模板和数据。例如,下面的代码将从一个名为MyTemplates.htm的文件中加在模板,从一个名为MyData.htm文件中加在一系列数据。
function showProducts() {
$.jTemplatesDebugMode(true);
// attach the template
$("#results").setTemplateURL("MyTemplate.htm");
// process the template
$("#results").processTemplateURL("MyData.htm");
}
MyTemplate.htm文件如下所示:
{#foreach $T.products as product}
Product Name: {$T.product.name}
Product Price: {formatPrice($T.product.price)}
{#/for}
jTemplates允许您可以在一个单一文件定义多个模板,虽然在MyTemplate.htm文件没有演示此功能。
最后,MyData.htm文件如下所示:
{"products": [
{ "name": "Laptop", "price": "788.67" },
{ "name": "Comb", "price": 2.50 },
{ "name": "Pencil", "price": 1.99 }
] }
当然,包含在MyData.htm的内容有数据库动态生成。
mplate模板可以包含诸如#foreach、#for、and #if的特殊命令。至于调用formatPrice()函数,它表明模板也可以包含任意JavaScript函数的调用。