网络编程
位置:首页>> 网络编程>> JavaScript>> jQuery模板提案(9)

jQuery模板提案(9)

作者:dishuipiaoxiang 来源:Denis'Blog 发布时间:2010-03-30 18:27:00 

标签:jquery,模板,Javascript,对象

代码块

除了表达式,你可以在模板中插入代码执行自定义逻辑、条件或循环。代码块用{%....%}语法来分隔(没有=)。

示例

这个例子显示系列产品的name,如果有可用的“specials”则显示。

<script type="text/html" id="tmp1">
<li>
    {%= name %}
    {% if (specials.length) { %}
    <ul>
    {% for (var i = 0, l = specials.length; i < l; i++) { %}
        <li>{%= specials[i].details %}</li>
    {% } %}
    </ul>
    {% } %}
</li>
</script>

 

上下文

在模板中,你可以使用一个名叫$context 的特殊变量,这与提案后面要描述的rendering和rendered回调是同一个对象。$context具有以下属性:

参数描述
data传递给render()和append()函数的数组或对象
dataItem但是,这个放到with() 块中,使得数据的每一个字段可以直接使用。例如,如果数据为[{name:"dave"},{name:"bob"}] ,那么{%= name } 就可以使用。但是要注意,指向一个不存在的字段将是无效的。数据为[{name:"dave"},{firstname:"bob"}] ,那么第二个表达式“name”将无效。
index传递给模板的当前数据项在数组中的索引。如果是一个对象,索引为0
options传递给模板的选项参数。这个提供了给模板传递额外参数的方法。

你对$context 变量的修改在模板中将保持一致。例如,你可以在render()函数中给$context 变量添加计算字段。

function rendering(context) {
  context.tax = context.dataItem.price * 0.23;
}

你可以在模板中使用tax计算字段,保持模板简单,避免需要调试的内嵌表达式。

<script type="text/html" id="tmp1">
  The product with tax costs {%= $context.tax %}
</script>

你可以使用$context.options变量指向任何需要传递给render()和append()函数的选项。下面的示例演示了如何根据传递给append()函数的showSalePrice 参数值来显示正常价格或零售价格。

<script type="text/javascript">
    jQuery(function() {
        var products = [
            { name: "Product 1", price: 12.99, salePrice: 10.99 },
            { name: "Product 2", price: 9.99, salePrice: 7.99 },
            { name: "Product 3", price: 35.59, salePrice: 33.59 }
        ];
        $("ul").append("#template", products, { showSalePrice: true });    
    });
</script>
<script id="template" type="text/html">
 <li>
     {%= name %} - 
     {%= $context.options.showSalePrice ? salePrice : price %}
 </li>
</script>
<ul></ul>

注意如何在模板中根据$ context.options.showSalePrice属性来显示正常价格或零售价格。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com