如何在ejs模板中设置标题?

How to set title in ejs template?

我尝试使用

设置标题
app.set('title', 'My Site');

并且在 ejs 模板中,我尝试使用它。

<h1 class="logo"><a href="index.html"><%= title %><span>.</span></a></h1>

但是,低于错误。

title is not defined
    at eval (eval at compile (D:\crypto_assets\node_modules\ejs\lib\ejs.js:662:12), <anonymous>:12:26)
    at header (D:\crypto_assets\node_modules\ejs\lib\ejs.js:692:17)
    at include (D:\crypto_assets\node_modules\ejs\lib\ejs.js:690:39)
    at eval (eval at compile (D:\crypto_assets\node_modules\ejs\lib\ejs.js:662:12), <anonymous>:18:17)
    at portfolio (D:\crypto_assets\node_modules\ejs\lib\ejs.js:692:17)
    at tryHandleCache (D:\crypto_assets\node_modules\ejs\lib\ejs.js:272:36)
    at View.exports.renderFile [as engine] (D:\crypto_assets\node_modules\ejs\lib\ejs.js:489:10)
    at View.render (D:\crypto_assets\node_modules\express\lib\view.js:135:8)
    at tryRender (D:\crypto_assets\node_modules\express\lib\application.js:640:10)
    at Function.render (D:\crypto_assets\node_modules\express\lib\application.js:592:3)

app.set() 用于定义名称及其值的设置,例如app.set('foo', 'bar') set the foovalue tobar. To access the setting value, you need to use app.get()method asapp.get('foo'). You can't just access it via name in app.js`(或任何其他)文件和模板中。

如评论中所述,您需要从渲染视图的位置传递 object 作为标题 属性。

router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

如果您正在寻找可以在所有模板中使用的变量,可以在中间件中使用 res.locals 属性 定义它,例如

app.use(function (req, res, next) {
  res.locals.title = "Marker";

  next();
});

有了这个,您现在可以在视图中使用 title