前端arttemplate模板引擎的用法

原生語(yǔ)法

使用原生語(yǔ)法,需要導(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ù)到頁(yè)面

    $('#main_panel').html(template('main_panel_big_sale_template', data));

    簡(jiǎn)潔語(yǔ)法

    使用簡(jiǎn)潔語(yǔ)法,導(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ù)到頁(yè)面,和原生語(yǔ)法一樣

    $('#main_panel').html(template('main_panel_big_sale_template', data));

    調(diào)用外部函數(shù)

    template.helper

    上面的例子中,都調(diào)用了formatPrice函數(shù),要調(diào)用此函數(shù)需要通過(guò)helper方法注冊(cè):

    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";

    }

    }

    });

    原生語(yǔ)法與簡(jiǎn)潔語(yǔ)法比較

    語(yǔ)法類型調(diào)用外部函數(shù)

    原生<%=formatPrice(product.promoPrice,'integer')%>

    簡(jiǎn)潔{{product.price.value | formatPrice: 'integer'}}

    簡(jiǎn)潔語(yǔ)法的傳參有點(diǎn)奇怪,原生語(yǔ)法就很好理解,如果要傳遞三個(gè)參數(shù),簡(jiǎn)潔語(yǔ)法該怎么寫(xiě)呢?

    簡(jiǎn)潔語(yǔ)法的循環(huán)如果要做更多邏輯,也實(shí)現(xiàn)不了

    推薦使用原生語(yǔ)法

    template.compile

    模板可以直接寫(xiě)在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;

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

    作者:ilaoke

    鏈接:http://www.itdecent.cn/p/483fa7f6f55b

    來(lái)源:簡(jiǎn)書(shū)

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

  • 最后編輯于
    ?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
    【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
    平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

    相關(guān)閱讀更多精彩內(nèi)容

    友情鏈接更多精彩內(nèi)容