如何在 Pug 中执行 NodeJS 函数

How to execute a NodeJS function in Pug

我有一些负责创建函数的节点 js 代码,我想在我的 .pug 模板中执行它。

let pages = [
    {
        "id": 0,
        "name": "Index"
    },
    {
        "id": 1,
        "name": "About"
    },
    {
        "id": 2,
        "name": "Kontakt"
    },
];

function navigation(pages) {
    return pages;
}


app.get("/", (req, res) => {
    res.write(navigation(pages));
    res.render("index");
});

如何在 pug 模板中调用此函数,或者将函数从 node 传递到 jade 的更好方法是什么?

假设您将 express.js 与 node.js、

一起使用

在node.js后端,写:

function navigation() {
  let pages = [
    {
      id: 0,
      name: "Index"
    },
    {
      id: 1,
      name: "About"
    },
    {
      id: 2,
      name: "Kontakt"
    }
  ];
  return pages;
}

app.get("/", (req, res) => {
  res.render("index", { navigation: navigation });
});

在哈巴狗模板中,写:

script !{navigation}

演示:https://glitch.com/edit/#!/pass-javascript-functions-from-node-js-to-pug

好吧,在那个答案和你的演示之间你几乎把我带到了我需要去的地方......现在的问题是我需要将一个变量传递给脚本。

当我使用下面的代码时,我得到

Uncaught ReferenceError: p is not defined

doctype html
html
  head
    title foobar
    script !{getProfile}
  body
    ul
      each p in profiles
        script.getProfile(p);

但如果这样做

doctype html
html
  head
    title foobar
    script !{getProfile}
  body
    ul
      each p in profiles
        li=p

一切正常。