美文网首页
nodejs使用ejs模板渲染的数组问题

nodejs使用ejs模板渲染的数组问题

作者: _鹅不食草_ | 来源:发表于2020-06-06 11:49 被阅读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 转换后结果也还是一样

图片

浏览器自动转换了,于是我想着把hotBrands转化成json字符串,如下:

 ···

 hotBrandList = JSON.stringify(hotBrandList);
hotBrands = JSON.parse('<%=hotBrandList%>');
console.log(hotBrands)

结果如下

图片

还是不能正常显示

最后我试着两着结合

  hotBrandList = encodeURIComponent(JSON.stringify(hotBrandList));
  hotBrands = JSON.parse(decodeURIComponent('<%=hotBrandList%>'));

结果如下:

图片

终于正常显示了,好坑。

所以在用模板渲染时要注意一些特殊数据类型或符号可能会被浏览器转换,如果遇到了需要特殊处理一下。

相关文章

网友评论

      本文标题:nodejs使用ejs模板渲染的数组问题

      本文链接:https://www.haomeiwen.com/subject/xumgzhtx.html