iT邦幫忙

13

寫了個簡單的Javascript模版引擎

因為工作需要兼練習,寫了一個簡單的Javascript模版引擎:https://github.com/fillano/fit

可以在伺服器端及瀏覽器端使用(工作上是在瀏覽器端使用),透過npm或bower都可以安裝:

用npm安裝的話:

npm install fit-template

用bower安裝的話:

bower install fit-template

因為工作需求簡單,所以功能也非常簡單,只支援賦值、foreach迴圈及if/else邏輯分支三種語法。沒有外部依賴,檔案也蠻小,壓縮後是3.7KB。

一個簡單的hello world範例:

var fit = require('fit-template');
var data = {name: 'fillano'};
var template = '<div>Hello {{=$name}}</div>';
var render = fit(template);
console.log(render(data));
//顯示:<div>Hello fillano</div>

其實一行也可以:

console.log(require('fit-template')('<div>Hello {{=$name}}</div>')({name: 'hildegard'}));
//顯示:<div>Hello hildegard</div>

至於是要練習什麼...

之前看過Douglas Crockford在美麗程式這本書中寫了一個「由上而下運算子優先權」的剖析器,引發了一點興趣,所以也想有機會時練習寫一個剖析器。這個模版引擎是用簡單的遞迴下降剖析器的方式實作,這樣要解決迴圈跟邏輯分支嵌套(Nested)好像比較容易/images/emoticon/emoticon06.gif。文組出來的邏輯比較差XD


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
海綿寶寶
iT邦大神 1 級 ‧ 2016-09-07 22:32:08

名不符實,扣分
/images/emoticon/emoticon15.gif

這麼專業的技術成果
怎麼可以用「簡單」二字形容?
不答應

別管大巨蛋要不要蓋還是拆了
大家趕快來按讚才對
/images/emoticon/emoticon12.gif/images/emoticon/emoticon12.gif/images/emoticon/emoticon12.gif

我要留言

立即登入留言