如何在 javascript 函数中使用已传递到 pug 模板的数组而不将其拆分?

How do I use an array that has been passed into a pug template, in a javascript function without it being split?

我有一个 CRUD.js 文件,我用它来将一些变量(包括数组)传递到名为 list.pug:

的哈巴狗模板中
router.get('/', async (req, res) => {
  let {projects, nextPageToken} = await db.list(10, req.query.pageToken);
  let customers = ["John", "Mary", "Mark"];

  res.render('projects/list.pug', {
    projects,
    nextPageToken,
    customers,
  });
});

然后在 pug 文件中,我试图通过遍历这些数组,使用 javascript 构建一个 table。然而,当我这样做时,似乎客户不是被视为一组字符串,而是被视为一个字符串(尝试循环项目时会发生类似的问题)。这是带有 javascript:

的哈巴狗模板
  select(name="customerDropdown", id="customerDropdown" class="btn btn-success dropdown-toggle" onChange="changeEvent()")
    each customer in customers 
      option=customer

  each project in projects
      .media
        a(href=`/projects/${project.id}`)
          .media-body
            h4= "Customer: " + project.customer
            p= "Project manager: " + project.manager

  if !projects.length
    p No projects found.

  if nextPageToken
    nav
      ul.pager
        li
          a(href=`?pageToken=${encodeURIComponent(nextPageToken)}`) More
 script.
    let projects = "!{projects}"
    let customers = "!{customers}"

    console.log(customers.length)
    for (var i = 0; i < customers.length; i++){
      console.log(customers[i])
    }

此代码导致打印出客户的每个字符(即'J'、'O'、'H'、'N'、','、'M', 等)而不是:“John”、“Mary”、“Mark”,尽管“customerDropdown”中的“each customer in customers”循环工作正常。我正在尝试使用这个数组来动态更新页面,那么如何将它作为原始数组而不是 string/array 个字符拉入 JS 函数?感谢任何帮助!

为了将数组从 Pug 传递到客户端 javascript,您需要去掉引号并在插值期间使用 JSON.stringify(),如下所示:

script.
  let projects  = !{JSON.stringify(projects)}
  let customers = !{JSON.stringify(customers)}