[Node.js] Server 傳送變數(參數)到 jade client

這篇記錄工作上遇到的問題

如何從 server 傳送變數到 jade client




1. Server 端 (.js)

res.render('product/create/' + req.params.type, {
    title: config.appName,
    series_list: config.device_series,
    device_list: devices,
});

這裡傳送了三個變數到 client: title, series_list, device_list

title(String): 'TITLE'
series_list(Object): ['series1', 'series2', 'series3']
device_list(Object): [['device1', 'device2'], ['device3'], [], ['device4']]

2. Client 端 (.jade)

div(class="form-inline")
    each zf in series_list
        span  #{zf}
        button(class='btn btn-secondary form-control',type='button',onclick='addDeviceSeries("#{zf}","#blockDeviceInput")')
                    span(class="glyphicon glyphicon-plus")

script.
    function addDeviceSeries(series, textInputId) {
        console.log(series);
        console.log(textInputId);
        var title = #{title};
        var series_list = !{JSON.stringify(series_list)};
        var device_list = !{JSON.stringify(device_list)};
        ...
    }


在 jade 裡面,要用變數在運算式(for, each, if, ...)直接打變數名稱就可以了
例如上面的 eash zf in series_list

而要用在網頁文字(p, span, h1, ...)則必須要用 #{變數}
例如 span #{zf}


在 script 裡,要用傳過來的變數有兩種形式
#{變數} 和 !{變數}
# 裡面只能是字串,如果傳 object 會報錯
object 必須用 ! 加上 JSON.stringify


不論在 jade 或 script 裡,大括號裡都可以是 javascript
例如:
三項運算式
input(class="form-control",type='text',value='#{product ? product.availableDevice:""}')

replace
var users = !{JSON.stringify(users).replace(/<\//g, "<\\/")}

toUpperCase
- var msg = "not my inside voice";
p This is #{msg.toUpperCase()}

參考:
https://naltatis.github.io/jade-syntax-docs/
https://stackoverflow.com/questions/8698534/how-to-pass-variable-from-jade-template-file-to-a-script-file
http://jade-lang.com/reference/interpolation
https://github.com/pugjs/pug/blob/355d3dae/examples/dynamicscript.pug

留言

熱門文章