Tarang Hirani
Tarang Hirani

Reputation: 590

expressJs default value of title variable declaration

Where does express get the default value for its title variable. My index.jade looks like the following:

    h1= title
p Welcome to #{title}

I don't quite understand where the title variable is set.

Upvotes: 2

Views: 2731

Answers (3)

mscdex
mscdex

Reputation: 106696

You can set view variables at the app level, the response level, and/or at the time of render.

Upvotes: 2

Stephen Byrne
Stephen Byrne

Reputation: 7485

In express, the template (.jade for example) has access to

  • anything in app.locals which are basically global variables
  • anything in res.locals which are tied to the request/response cycle of the current request
  • anything passed to it via res.render() which will have typically been determined in your request route handler

Just to expand on this, here is an example that should demonstrate:

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}

When you visit http://localhost:3000/[some value] you will see the values of app.locals.globalVar, res.locals.resLocalVar, and also the value of renderVar that's defined in the call to res.render() in index.js.

Upvotes: 3

Mritunjay
Mritunjay

Reputation: 25892

In your routes/index.js you will be saying

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

So here it will find views/index.jade put value of title variable as 'Express'.

You can say in your jade

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

and while renderring

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

it will be converted in Welcome to Express from myName.

Upvotes: 4

Related Questions