Product Name: <%= name %>
<br />
Product Price: <%= formatPrice(price) %>
</script>
<div id="results"></div>
注 意,
SCRIPT 的 type 属性 为 “text/ html”。用 这种 方式 来声 明 web 浏览 器会 忽略
SCRIPT 里的内容,将其内容当作字符串来对待。
注意,模板包含代表产品名称和价格属性的表达式。调用
JavaScript 的 formatPrice()
方法来格式化产品的价格。在模板里你可以调用任何
JavaScript 函数。
这里是如何渲染一个
product 对象数组的示例:
function showProducts() {
// parse the template
var template = tmpl("productTemplate");
// loop through the products
var results = '';
for (var i = 0; i < products.length; i++) {
results += template(products[i]);
}
// show the results
$("#results").html(results);
}
tmpl()函数支持 currying(关于什么 currying,可以在网上查阅资料)。如果没有提供数据
给
tmpl()函数,他将返回一个 javascript 函数,代表解析的模板。
在上面的代码中,模板被解析,然后为每一个
product 调用模板方法生成一个字符串。
最后,字符串分配给名叫
results 的 div 元素的 innerHTML。