【问题标题】:how to get locals in Express from routes如何从路线中获取 Express 中的当地人
【发布时间】:2015-08-14 12:46:02
【问题描述】:

我在我的 app.js 文件中定义了一个本地变量,如下所示(应用程序真的很快速):

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

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

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

console.log(express.locals);

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

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    documentation 声明:

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

    换句话说,您无需执行任何特殊操作即可将 weather 传递给您的 EJS 模板,只需将其分配给 app.locals 即可通过您的应用程序使用它。

    【讨论】:

    • 但它没有渲染...我正在做: 它是空白的,我写的是本地人。天气而不是只有天气,因为在第二种情况下发生了错误......
    【解决方案2】:

    在 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>
    

    它有效

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2016-04-08
      • 2013-02-02
      相关资源
      最近更新 更多