前端arttemplate模板引擎的用法

原生語法

使用原生語法,需要導(dǎo)入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));

    簡潔語法

    使用簡潔語法,導(dǎo)入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;

    這種方式的的缺點是,模板通過字符串拼接,不好維護(hù),適合簡單模板。

    作者:ilaoke

    鏈接:http://www.lxweimin.com/p/483fa7f6f55b

    來源:簡書

    著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

  • 最后編輯于
    ?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
    平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

    推薦閱讀更多精彩內(nèi)容