上下文
在模板中,你可以使用一个名叫$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属性来显示正常价格或零售价格。
出处:Denis'Blog
责任编辑:moby
上一页 jQuery模板提案 [7] 下一页 jQuery模板提案 [9]
◎进入论坛网页制作、WEB标准化版块参加讨论,我还想发表评论。
|