expressJs标题变量声明的默认值

时间:2014-07-18 03:28:42

标签: node.js express pug

express在哪里获取其title变量的默认值。我的index.jade如下所示:

    h1= title
p Welcome to #{title}

我不太清楚标题变量的设置位置。

3 个答案:

答案 0 :(得分:4)

在你的routes/index.js中,你会说

res.render('index', { title: 'Express' });

所以在这里它会发现views/index.jadetitle变量的值设为'Express'

你可以在你的玉中说出

p Welcome to #{title} from #{name}

和渲染时

res.render('index', { title: 'Express' ,name: 'myName'});

它将在Welcome to Express from myName中转换。

答案 1 :(得分:2)

您可以在app levelresponse level和/或at the time of render设置视图变量。

答案 2 :(得分:1)

在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/[some value]时,您会看到app.locals.globalVarres.locals.resLocalVar的值,以及在调用res中定义的renderVar的值index.js中的.render()。