Juicer 中文文檔

Juicer 是一個高效、輕量的前端 (Javascript) 模板引擎,使用 Juicer 可以是你的代碼實現數據和視圖模型的分離(MVC)。 除此之外,它還可以在 Node.js 環境中運行。

你可以在遵守 MIT Licence 的前提下隨意使用並分發它。Juicer 代碼完全開源並託管在 Github 上,如果你在使用的過程中發現 什麼 Bug 抑或是一些好的建議都歡迎在 Github Issue 上提交。

名字的由來

倘若我們把數據比作新鮮可口的水果,把模板看做是水,Juicer 就是把水果和水榨出我們需要的HTML代碼片段的榨汁機。

Juicer 的引入

<script type="text/javascript" src="juicer-min.js"></script>

使用方法

編譯模板並根據所給的數據立即渲染出結果.

juicer(tpl, data);

僅編譯模版暫不渲染,它會返回一個可重用的編譯後的函數.

var compiled_tpl = juicer(tpl);

根據給定的數據,對之前編譯好的模板進行數據渲染.

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

註冊/註銷自定義函數(對象),在下邊 ${變量} 中會有實例.

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

自定義模板語法邊界符,下邊是 Juicer 默認的邊界符。你可以藉此解決 Juicer 模板語法同某些後端語言模板語法衝突的情況.

juicer.set({
    'tag::operationOpen': '{@',
    'tag::operationClose': '}',
    'tag::interpolateOpen': '${',
    'tag::interpolateClose': '}',
    'tag::noneencodeOpen': '$${',
    'tag::noneencodeClose': '}',
    'tag::commentOpen': '{#',
    'tag::commentClose': '}'
});

默認參數配置

{
    cache:          true [false],
    strip:          true [false],
    errorhandling:  true [false],
    detection:      true [false]
}

默認配置是 Juicer 推薦的使用方式,如果你使用過程中的確需要更改這些參數,可以這麼做:

逐條參數更改:

juicer.set('strip',false);
juicer.set('cache',false);

批量參數更改:

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

Juicer 默認會對編譯後的模板進行緩存,從而避免同一模板多次數據渲染時候重複編譯所耗的時間, 如無特殊需要,強烈不建議關閉默認參數中的 cache,這麼做將會令 Juicer 緩存失效從而降低性能.

語法

${變量}

使用 ${} 輸出變量值,其中 _ 爲對數據源的引用(如 ${_},常用於數據源爲數組的情況)。支持自定義函數(通過自定義函數你可以實現很多有趣的功能,類似 ${data|links} 就可以 通過事先定義的自定義函數 links 直接對 data 拼裝出<a href=".." alt=".." /> ).

${name}
${name|function}
${name|function, arg1, arg2}

讓我們通過一個例子演示一下自定義函數的奇妙用法吧.

var json = {
    links: [
        {href: 'http://juicer.name', alt: 'Juicer'},
        {href: 'http://benben.cc', alt: 'Benben'},
        {href: 'http://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);

上述代碼執行後我們會發現結果是這樣的:

<a href="http://juicer.name" alt="Juicer" <br />
<a href="http://benben.cc" alt="Benben" <br />
<a href="http://ued.taobao.com" alt="Taobao UED" <br />

可以看得出,結果被轉義了,如果我們上邊使用 $${item|links} 就會得到我們預期的結果,這就是下邊即將提到的避免轉義。

轉義/避免轉義 出於安全角度的考慮,${變量} 在輸出之前會對其內容進行轉義,如果你不想輸出結果被轉義,可以使用 $${變量} 來避免這種情況。 例如:

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

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

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

內聯輔助函數 {@helper} ... {@/helper}

如果你需要在頁面或者模板內定義輔助函數,可以像這樣使用 helper,同時支持Node和Browser.

<!--
{@helper numberPlus}
    function(number) {
        return number + 1;
    }
{@/helper}
-->

Javascript 代碼:

var tpl = 'Number: ${num|numberPlus}';

juicer(tpl, {
    num: 123
});
//輸出 Number: 124

循環遍歷 {@each} ... {@/each}

如果你需要對數組進行循環遍歷的操作,就可以像這樣使用 each .

{@each list as item}
	${item.prop}
{@/each}

如果遍歷過程中想取得當前的索引值,也很方便.

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

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

我們也會經常碰到對數據進行邏輯判斷的時候.

{@each list as item,index}
    {@if index===3}
        the index is 3, the value is ${item.prop}
    {@else if index === 4}
        the index is 4, the value is ${item.prop}
    {@else}
        the index is not 3, the value is ${item.prop}
    {@/if}
{@/each}

註釋 {# 註釋內容}

爲了後續代碼的可維護性和可讀性,我們可以在模板中增加註釋.

{# 這裏是註釋內容}

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

輔助循環是 Juicer 爲你精心設置的一個語法糖,也許你會在某種情境下需要它.

{@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'
    }
});

在 Node.js 環境中運行

在命令行中執行:

npm install juicer

在代碼中這麼引入:

var juicer = require('juicer');
var html = juicer(tpl, data);

在 express.js 框架中使用

在 express 2.x 系列版本中:

npm install juicer
var juicer = require('juicer');
app.set('view engine', 'html');
app.register('.html', {
    compile: function(str, options) {
        return juicer.compile(str, options).render;
    }
});

在 express 3.x 系列版本中:

npm install juicer
var juicer = require('juicer');
var fs = require('fs');
app.set('view engine', 'html');
app.engine('html', function(path, options, fn){
    fs.readFile(path, 'utf8', function(err, str){
        if (err) return fn(err);
        str = juicer(str, options);
        fn(null, str);
    });
});

或者也可以藉助 juicer-express-adapter 中間件在Node端使用Juicer以及簡單的include功能。

npm install juicer-express-adapter

在命令行預編譯模板文件:

npm install -g juicer
juicer example.juicer.tmpl -f example.js
// type `juicer` after install for more help.
// 全局模式安裝 `juicer` 後,在命令行下輸入 `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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章