【问题标题】:expressJs default value of title variable declarationexpressJs 标题变量声明的默认值
【发布时间】:2014-07-18 23:11:57
【问题描述】:

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

    h1= title
p Welcome to #{title}

我不太明白 title 变量的设置位置。

【问题讨论】:

    标签: node.js express pug


    【解决方案1】:

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

    【讨论】:

    • 知道了。这很有意义。
    【解决方案2】:

    在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 的值,以及在 index.js 中对 res.render() 的调用中定义的 renderVar 的值。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多