3

Starting my way in node + express, what's the difference between:

app.set(key, value)

and

app.locals({key: value});

I've read the express docs and it states that app.locals are passed to all the rendered views, but I was also able to access the settings from a jade view as well (using #{settings.someKey}). As both are available in jade templates I can't seem to figure out what the difference or different usage for the 2.

4

1 回答 1

3

The difference is that by manipulating app.locals directly, you can create 'top level' variables for your templates, instead of having to use the settings. prefix.

app.set(key, value) is the same as app.locals.settings[key] = value; the former is the preferred way of configuring certain parts of Express (like setting view engine).

EDIT: small demo to show how they do the same:

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

app.set('foo', 'bar');
console.log('app.get("foo"):', app.get('foo')); // 'bar'
console.log('app.locals.settings.foo:', app.locals.settings.foo); // 'bar'
app.locals.settings['foo'] = 'another bar';
console.log('2nd app.get("foo"):', app.get('foo')); // 'another bar'
于 2013-03-20T13:19:15.417 回答