首页 > 解决方案 > 处理程序栏访问数组变量

问题描述

我正在 Express 应用程序中使用 Handlebars。从服务器端,我将日期数组作为字符串传递:

reqCtrl.dateController = async (req, res) => {
...
var dates = [
    "2020-09-27",
    "2020-09-28",
    "2020-09-29",
    "2020-09-30",
    "2020-10-01",
    "2020-10-02",
    "2020-10-03",
    "2020-10-04",
  ];

  console.log(dates);
  //Resulting in: ['2020-09-27', '2020-09-28', '2020-09-29', '2020-09-30', '2020-10-01', '2020-10-02', '2020-10-03', '2020-10-04']
  res.render("requests/...", 
    dates
  });
}

但是,在客户端,使用以下表达式我得到不同的值。

<script>
console.log({{ dates }})
//Resulting in:  1984 1983 1982 1981 2009 2008 2007 2006
</script>

我错过了什么吗?如何呈现格式正确的日期?

标签: javascriptnode.jsexpresshandlebars.js

解决方案


如果您 render<p>{{dates}}</p>而不是控制台记录它会发生什么?无论哪种方式,您都可能希望在使用把手时遍历数组以进行渲染。这是通过#each完成的。

<ul>
  {{ #each dates}}
    <li>{{this}}</li>
  {{/each}}
</ul>
  

推荐阅读