【问题标题】:Best Practice for Headers/Footer/Reusable Templates in Node.JS/Express Views?Node.JS/Express 视图中页眉/页脚/可重用模板的最佳实践?
【发布时间】:2023-03-26 13:58:02
【问题描述】:

我用 Node.JS / Express / Pug 设置了我的开发环境,我正在学习如何使用视图和路由,但我找不到关于如何包含“可重用”导航栏和页脚。

在 PHP 中,您只需包含 header.php 和 footer.php 文件,它会将它们拉入每个页面,在 Node/Express 中执行此操作的最佳方法是什么?

我看到术语“局部视图”被抛出,但与页眉和页脚无关,所以我正在寻找实现这一目标的最佳方法。

假设我有 3 个视图:索引、关于和联系我如何在所有 3 个视图中包含相同的导航栏和页脚而不将其复制并粘贴到每个视图中?只需要朝着正确的方向努力。

提前致谢

【问题讨论】:

标签: javascript node.js express templates middleware


【解决方案1】:

要撰写回复,您有几个选择:

1) 让模板引擎完成它的工作:

  doctype html
  html
    include includes/head.pug

文档

2) 使用 express 一次发送多个文件:

  app.use((req, res, next) => {
    const header = fs.createReadStream("header.html");
    header.pipe(res);
    header.on("close", next);
  });

  app.get("/", (req, res, next) => {
    // Send the homepage
  });

  //....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 2021-01-10
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多