jTemplates初步接触

 jTemplates

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>,那么,名称将被转换成&lt;b&gt;Laptop&lt;/b&gt; 。

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函数的调用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值