nodejs使用ejs模板渲染的数组问题
2020-06-06 本文已影响0人
_鹅不食草_
在用ejs模板进行渲染时遇到这样一个问题,nodejs端返回一个数组,在模板渲染出来的结果不是想要的数据,如下:
let hotBrandList = [];
let hotBrandIds = [];
//获取热门品牌id
let _hotBrandList = yield autopriceFunc.getHotBrands();
if(_hotBrandList.data.code == 0) {
hotBrandIds = _hotBrandList.data.data.list;
for(let i=0; i<hotBrandIds.length; i++) {
let bItem = yield autopriceFunc.getBrandInfo(hotBrandIds[i], {id:'',name:'',logo96x96:''});
hotBrandList.push(bItem);
}
}
console.log(hotBrandList);
模板里是这样的
hotBrands = <%=hotBrandList%>;
console.log(hotBrands)
hotBrands
应该是一个对象数组,结果打印出来的结果是下图这样的,用 encodeURIComponent
转换后结果也还是一样
![](https://img.haomeiwen.com/i18968697/2c81899c22c334af.png)
浏览器自动转换了,于是我想着把hotBrands
转化成json
字符串,如下:
···
hotBrandList = JSON.stringify(hotBrandList);
hotBrands = JSON.parse('<%=hotBrandList%>');
console.log(hotBrands)
结果如下
![](https://img.haomeiwen.com/i18968697/5bada4b3933c916c.png)
还是不能正常显示
最后我试着两着结合
hotBrandList = encodeURIComponent(JSON.stringify(hotBrandList));
hotBrands = JSON.parse(decodeURIComponent('<%=hotBrandList%>'));
结果如下:
![](https://img.haomeiwen.com/i18968697/4a22288a72eb56c4.png)
终于正常显示了,好坑。
所以在用模板渲染时要注意一些特殊数据类型或符号可能会被浏览器转换,如果遇到了需要特殊处理一下。