【问题标题】:How to execute a NodeJS function in Pug如何在 Pug 中执行 NodeJS 函数
【发布时间】:2020-07-05 09:04:46
【问题描述】:

我有一些负责创建函数的节点 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 模板中调用此函数,或者将函数从节点传递到玉的更好方法是什么?

【问题讨论】:

  • @xMayank 是的,有点

标签: node.js pug


【解决方案1】:

假设您将 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

【讨论】:

    【解决方案2】:

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

    当我使用以下代码时,我得到了

    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
    

    一切都很完美。

    【讨论】:

    • 我强烈怀疑您在这里混淆了客户端和服务器端脚本。这些配置文件来自哪里?您究竟希望 getProfile 做什么?
    猜你喜欢
    • 1970-01-01
    • 2018-03-22
    • 2017-09-02
    • 2015-04-14
    • 2017-10-23
    • 2023-01-16
    • 2021-02-25
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多