Node.js expressJs标题变量声明的默认值

Node.js expressJs标题变量声明的默认值,node.js,express,pug,Node.js,Express,Pug,express从何处获取其title变量的默认值。我的index.jade如下所示: h1= title p Welcome to #{title} 我不太明白title变量设置在哪里 您可以在您的routes/index.js中的、和/或处设置视图变量 res.render('index', { title: 'Express' }); 因此,在这里它将找到视图/index.jade将标题变量的值设置为'Express' 你可以说在你的玉 p Welcome to #{title}

express从何处获取其title变量的默认值。我的index.jade如下所示:

    h1= title
p Welcome to #{title}

我不太明白title变量设置在哪里

您可以在您的
routes/index.js
中的、和/或处设置视图变量

res.render('index', { title: 'Express' });
因此,在这里它将找到
视图/index.jade
标题
变量的值设置为
'Express'

你可以说在你的玉

p Welcome to #{title} from #{name}
在渲染时

res.render('index', { title: 'Express' ,name: 'myName'});
它将在
中转换,欢迎使用myName的Express

在express中,模板(.jade)可以访问

  • app.locals
    中基本上是全局变量的任何内容
  • res.locals
    中与当前请求的请求/响应周期相关的任何内容
  • 通过res.render()传递给它的任何内容,通常在请求路由处理程序中确定
为了进一步说明这一点,以下是一个示例:

app.js:

var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');

var app = express();
    //set a global variable that will be available to anything in app scope
app.locals.globalVar = "GLOBAL";
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.urlencoded());
app.use(express.methodOverride());
//register a middleware that will set a local variable on the response
app.use(function (req, res, next) {
    res.locals.resLocalVar = new Date();
    next();
});
app.use(app.router);

app.get('/', routes.index);
app.get('/:id', routes.index);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
index.js:

exports.index = function (req, res) {
    var id = req.params.id || "Nothing"
    res.render('index', { renderVar: id });
};
index.jade:

extends layout

block content
 p I am a global variable with value: #{globalVar}
 p I am scoped to the current request/response with value: #{resLocalVar}
 p I am only set on the call to render() in index.js and my value is: #{renderVar}

当您访问
http://localhost:3000/[一些值]
您将看到
app.locals.globalVar
res.locals.resLocalVar
,以及在index.js中调用res.render()时定义的
renderVar
的值。

明白了。这很有道理。