[handlebars筆記]基本介紹與helper應用
此處的handlebars是指express框架下的express-handlebars
express-handlebars是跟express框架搭配的module,是一個樣版引擎,可以用來解析html&css,並渲染成網頁。此外,handlebars亦可用來引入後端所接收到的資料(API檔、網頁參數、種子data…etc),並傳到前端做使用。
從後端傳入參數方式
在app.js中,使用render渲染網頁”index”,傳入參數使用 {data}
網頁中引入參數方式為{{data.num1}}
{{}}單純引入參數
{{{}}}解析html網頁
handlebars內建判斷式
handlebars有內建個基本的helper可以使用:if、unless、with及each
if語法 = 單純判斷變數是否存在,存在則中間html會被解析
Example:
data = { num1: 20 };
{{#if data.num1}} //開頭<p>{{data.num1}} 存在</p>{{/if}} //結尾
可搭配else使用
{{#if data.num2}}<p>{{data.num2}}</p>{{else}}<p>No content</p> //No content{{/if}}
unless語法 =單純判斷變數是否存在,若存在則中間html會被解析
Example:
data = { num1: 20 }
{{#unless data.num1}} //變數存在<p>{{data.num1}} 不存在</p> //不解析{{/unless}}
{{#unless data.num2}} //變數不存在<p>{{data.num2}} 不存在</p> //解析{{/unless}}
with語法 = 列出object內value值
data = { name: “ni” , birthday: “420”}
{{#with datainside as |data|}}<p>{{data.name}}{{data.birthday}}</p> // ni 420{{/with}}
each語法 = 類似for迴圈
sample = [1, 2, 3, 4, 5];
{{#each sample}}<p>{{this}}</p> // 1 2 3 4 5{{/each}}
可搭配else使用,sample= []
{{#each sample}}<p>{{this}}</p>{{else}}<p>No content</p> //當sample無資料時顯示{{/each}}
handlebars 自訂 helper
除了上述內建helper,handlebars可以自訂helper
可以開啟一個新的js檔案,在內撰寫所需的helper,然後引入app.js
Example:
let sample = {num1: 5,num2: 4}
"test" : helper 名稱
function(a,b,options) : a,b為可傳入變數
options.fn(this) :handlebars內文字,出現在條件成立
options.inverse(this) :handlebars內文字,出現條件不成立
產生結果為: 5(sample.num) 比較大
//常用handlebars helperconst Handlebars = require("handlebars");Handlebars.registerHelper("test", function(left, operator, right, options) {if (arguments.length < 3) {throw new Error('Handlerbars Helper "compare" needs 2 parameters');}var operators = {"==": function(l, r) {return l == r;},"===": function(l, r) {return l === r;},"!=": function(l, r) {return l != r;},"!==": function(l, r) {return l !== r;},"<": function(l, r) {return l < r;},">": function(l, r) {return l > r;},"<=": function(l, r) {return l <= r;},">=": function(l, r) {return l >= r;},typeof: function(l, r) {return typeof l == r;}};if (!operators[operator]) {throw new Error('Handlerbars Helper "compare" doesn\'t know the operator ' + operator);}var result = operators[operator](left, right);if (result) {return options.fn(this);} else {return options.inverse(this);}});
handlebars helper中可以一次傳入多個變數,以上最常用的handlebars-helper中可以自訂operator,只要在需要使用時把operator當作string傳入即可
參考資料: