Swig支持自定義filter和tag疏咐,可以將內(nèi)容個性化担扑。
假如我們需要展示成這樣:
其中的“狀態(tài)”字段琴许,可以通過swig的自定義filter功能,將其渲染在頁面上晾浴,而不需要在頁面上直接寫html代碼负乡。
ok,我們自定義一個filter:
swig.setFilter('status', function(input) {
if(input) {
return '<span class="label label-primary">有效</span>'
}else{
return '<span class="label label-danger">無效</span>'
}
});
頁面上通過我們自定義的status filter顯示:
{{ a.status | status}}
結(jié)果大大出乎我們的意料:
沒錯脊凰,直接將html代碼當(dāng)作文本輸出了抖棘!顯然這不是我們想要的結(jié)果,那么怎么解決這個問題呢狸涌?
翻閱文檔切省,我們發(fā)現(xiàn)有一個autoescape
標(biāo)簽,官方解釋:Control auto-escaping of variable output from within your templates.杈抢,意思就是說自動控制輸出的轉(zhuǎn)義。那么能不能解決我們的問題呢仑性?答案是肯定的惶楼,完美解決了我們的問題!
{% autoescape %}{{ a.status | status}}{% endautoescape %}
關(guān)于autoescape的更多內(nèi)容诊杆,請參考:http://paularmstrong.github.io/swig/docs/tags/#autoescape