DIV CSS 佈局教程網

輕量級 JavaScript 模板引擎 juicer 使用指南
編輯:關於JavaScript     

juicer 是一個簡單又高效的 JS 模板引擎。以下依序整理用法、語法與完整範例。

基本用法

編譯模板並立即依資料渲染:

juicer(tpl, data);

僅編譯暫不渲染,回傳一個可重複使用的函式:

var compiled_tpl = juicer(tpl);

用給定的資料渲染先前編譯好的模板:

var complied_tpl = juicer(tpl);
var html = complied_tpl.render(data);

註冊/註銷自訂函式:

juicer.register('function_name', function);
juicer.unregister('function_name');

預設參數設定

{
    cache:          true,    // 是否快取編譯結果
    script:         true,    // 是否 ...
    error handling: true,    // 錯誤處理
    detection:      true     // 偵測
}

逐條修改:

juicer.set('cache', false);

批次修改:

juicer.set({ 'script': false, 'cache': false });

juicer 預設會快取編譯後的模板,避免同一模板多次渲染時重複編譯所耗費的時間。除非有特殊需求,強烈不建議關閉 cache,這麼做會令快取失效並降低效能。

語法

輸出變數:使用 ${} 輸出變數,其中 _ 為對資料源的引用(${_})。支援使用自訂函式:

${name}
${name|function}
${name|function, arg1, arg2}
var json = {
    links: [
        { href: 'https://juicer.name', alt: 'Juicer' },
        { href: 'https://benben.cc',   alt: 'Benben'  },
        { href: 'https://ued.taobao.com', alt: 'Taobao UED' }
    ]
};

var tpl = [
    '{@each links as item}',
        '${item|links_build} <br />',
    '{@/each}'
].join('');

var links = function (data) {
    return '<a href="' + data.href + '" alt="' + data.alt + '">';
};

juicer.register('links_build', links);   // 註冊自訂函式
juicer(tpl, json);

轉義與避免轉義:${變量} 在輸出前會對內容進行轉義;若不希望結果被轉義,可用 $${變量}:

var json = { value: '<strong>juicer</strong>' };

var escape_tpl   = '${value}';
var unescape_tpl = '$${value}';

juicer(escape_tpl, json);    // 輸出 '&lt;strong&gt;juicer&lt;/strong&gt;'
juicer(unescape_tpl, json);  // 輸出 '<strong>juicer</strong>'

循環遍歷 {@each} ... {@/each}:遍歷陣列,${index} 為當前索引:

{@each list as item, index}
    ${item.prop}
    ${index}   // 當前索引
{@/each}

條件判斷 {@if} ... {@else if} ... {@else} ... {@/if}

註解 {# 註解內容}:

{# 這裡是註解內容}

輔助循環 {@each i in range(m, n)}:

{@each i in range(5, 10)}
    ${i};   // 輸出 5;6;7;8;9;
{@/each}

子模板嵌套 {@include tpl, data}:除了引入資料中指定的子模板,也可以透過 #id 使用寫在 script 標籤中的模板程式碼。

HTML 程式碼:

<script type="text/juicer" id="subTpl">
    I'm sub content, ${name}
</script>

JavaScript 程式碼:

var tpl = 'Hi, {@include "#subTpl", subData}, End.';
juicer(tpl, { subData: { name: 'juicer' } });
// 輸出:Hi, I'm sub content, juicer, End.

// 或者透過資料引入子模板,下述程式碼將有相同的渲染結果:
var tpl = 'Hi, {@include subTpl, subData}, End.';
juicer(tpl, {
    subTpl: "I'm sub content, ${name}",
    subData: { name: 'juicer' }
});

一個完整的例子

HTML 程式碼:

<script id="tpl" type="text/template">
<ul>
    {@each list as it, index}
    <li>${it.name} (index: ${index})</li>
    {@/each}

    {@each blah as it}
    <li>
        num: ${it.num} <br />
        {@if it.num == 3}
            {@each it.inner as it2}
                ${it2.time} <br />
            {@/each}
        {@/if}
    </li>
    {@/each}
</ul>
</script>

JavaScript 程式碼:

var data = {
    list: [
        { name: 'guokai',    show: true  },
        { name: 'benben',    show: false },
        { name: 'dierbaby',  show: true  }
    ],
    blah: [
        { num: 1 },
        { num: 2 },
        { num: 3, inner: [
            { 'time': '15:00' },
            { 'time': '16:00' },
            { 'time': '17:00' },
            { 'time': '18:00' }
        ]},
        { num: 4 }
    ]
};

var tpl = document.getElementById('tpl').innerHTML;
var html = juicer(tpl, data);

使用這類模板引擎時務必留意轉義行為:預設 ${} 會做 HTML 轉義(這是防 XSS 的重要防線),只有在你確定內容可信、且本身就需要輸出 HTML 標籤時,才用 $${} 關閉轉義。若把使用者輸入的內容用 $${} 輸出,等於直接開了 XSS 的大門。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved