【发布时间】:2014-07-18 23:11:57
【问题描述】:
express 在哪里获取其标题变量的默认值。我的 index.jade 如下所示:
h1= title
p Welcome to #{title}
我不太明白 title 变量的设置位置。
【问题讨论】:
express 在哪里获取其标题变量的默认值。我的 index.jade 如下所示:
h1= title
p Welcome to #{title}
我不太明白 title 变量的设置位置。
【问题讨论】:
在你的routes/index.js 你会说
res.render('index', { title: 'Express' });
所以在这里它会找到views/index.jade把title变量的值作为'Express'。
你可以说你的玉
p Welcome to #{title} from #{name}
在渲染时
res.render('index', { title: 'Express' ,name: 'myName'});
它将转换为Welcome to Express from myName。
【讨论】:
在express中,模板(例如.jade)可以访问
app.locals 中的任何内容,基本上都是全局变量res.locals 中与当前请求的请求/响应周期相关的任何内容只是为了扩展这一点,下面是一个应该演示的示例:
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.globalVar、res.locals.resLocalVar 的值,以及在 index.js 中对 res.render() 的调用中定义的 renderVar 的值。
【讨论】:
您可以在app level、response level 和/或at the time of render 处设置视图变量。
【讨论】: