如何从路线到Express的本地人

时间:2015-08-14 12:46:02

标签: javascript node.js express

我的app.js文件中有一个像本地一样定义的变量(app非常明确):

app.locals.weather = { /* unimportant content here */ };

现在,我想从index.js路径访问该信息,以便在ejs模板上打印。我尝试过这个,但它说未定义:

var express = require('express');
var router = express.Router();

console.log(express.locals);

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

documentation州:

  

您可以访问应用程序中呈现的模板中的局部变量。

换句话说,您无需执行任何特殊操作即可将make VERBOSE=1 传递给EJS模板,方法是将其分配给weather,然后通过您的应用将其提供给您。

答案 1 :(得分:1)

在app.locals下创建的所有密钥都可直接用于模板。

在您的模板中,您不应将其称为locals.weather,而只是尝试weather

var express = require('express');
var app = express();

app.set('view engine', 'ejs');
app.set('views', __dirname + '/templates');
app.locals.weather = 'hot';

app.get('/', function(req, res){
    console.log('received req');
    res.render('hello');
});

app.listen(3000)

和ejs模板

<!DOCTYPE html>
<div>
    hello ejs
</div>
<div>
    <%= weather %>
</div>

它有效