原生語法
使用原生語法亏娜,需要導入template-native.js文件焕窝。
在HTML中定義模板,注意模板的位置维贺,不要放到被渲染區(qū)域它掂,防止模板丟失。
<% for (var i = 0; i < products.length; i ++) { %>
<% var product =products[i]; %>
<% if (i < 3) { %>
2015-02-09
<%=product.name%>
<%=product.description%>

¥ <%=formatPrice(product.promoPrice,'integer')%><%=formatPrice(product.promoPrice,'decimal')%>
<% } %>
<% } %>
template(id, data)
渲染數(shù)據(jù)到頁面
$('#main_panel').html(template('main_panel_big_sale_template', data));
簡潔語法
使用簡潔語法溯泣,導入template.js文件虐秋。
{{each products as product i}}
{{if i < 3}}
2015-02-09
{{product.name}}
{{product.description}}

¥ {{product.price.value | formatPrice: 'integer'}}{{product.price.value | formatPrice: 'decimal'}}
{{/if}}
{{/each}}
渲染數(shù)據(jù)到頁面,和原生語法一樣
$('#main_panel').html(template('main_panel_big_sale_template', data));
調(diào)用外部函數(shù)
template.helper
上面的例子中垃沦,都調(diào)用了formatPrice函數(shù)客给,要調(diào)用此函數(shù)需要通過helper方法注冊:
template.helper('formatPrice', function(price, type) {
if(price){
var arrayPrice = price.toString().split(".");
if(type == 'integer') {
return arrayPrice[0]?arrayPrice[0]:"0";
}else if (type =='decimal') {
return arrayPrice[1]?arrayPrice[1].length == 1?"."+arrayPrice[1]+"0":"."+arrayPrice[1]:".00";
}
}else{
if(type == 'integer') {
return "0";
}else if (type =='decimal') {
return ".00";
}
}
});
原生語法與簡潔語法比較
語法類型調(diào)用外部函數(shù)
原生<%=formatPrice(product.promoPrice,'integer')%>
簡潔{{product.price.value | formatPrice: 'integer'}}
簡潔語法的傳參有點奇怪,原生語法就很好理解栏尚,如果要傳遞三個參數(shù)起愈,簡潔語法該怎么寫呢?
簡潔語法的循環(huán)如果要做更多邏輯译仗,也實現(xiàn)不了抬虽。
推薦使用原生語法
template.compile
模板可以直接寫在JS中,再編譯渲染纵菌。
var source = '
'
+? ? '<% for (var i = 0; i < list.length; i ++) { %>'
+? ? ? ? '
索引 <%= i + 1 %> :<%= list[i] %>
'
+? ? '<% } %>'
+ '';
var render = template.compile(source);
var html = render({list: ['攝影', '電影', '民謠', '旅行', '吉他']});
document.getElementById('content').innerHTML = html;
這種方式的的缺點是阐污,模板通過字符串拼接,不好維護咱圆,適合簡單模板笛辟。
作者:ilaoke
鏈接:http://www.reibang.com/p/483fa7f6f55b
來源:簡書
著作權歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權序苏,非商業(yè)轉(zhuǎn)載請注明出處手幢。