view.js
This file
Path
lib/view.js
436 lines · 10.0 KiB · JavaScript
Last changed by
fixed app.locals precedenceTj Holowaychukbefore adoption509601e
History of this fileTake it
The walk stopped after 200 commits: lines older than 0477a53 point at it.
misc refactorTj Holowaychukbefore adoption0477a53
lines 1–36why, one step back12/*!3 * Express - view4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var path = require('path')13 , extname = path.extname14 , dirname = path.dirname15 , basename = path.basename16 , utils = require('connect').utils17 , View = require('./view/view')18 , partial = require('./view/partial')19 , union = require('./utils').union20 , merge = utils.merge21 , http = require('http')22 , res = http.ServerResponse.prototype;2324/**25 * Expose constructors.26 */2728exports = module.exports = View;2930/**31 * Export template engine registrar.32 */3334exports.register = View.register;3536/**Merge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e
lines 37–63why, one step back37 * Lookup and compile `view` with cache support by supplying38 * both the `cache` object and `cid` string,39 * followed by `options` passed to `exports.lookup()`.40 *41 * @param {String} view42 * @param {Object} cache43 * @param {Object} cid44 * @param {Object} options45 * @return {View}46 * @api private47 */4849exports.compile = function(view, cache, cid, options){50 if (cache && cid && cache[cid]) return cache[cid];5152 // lookup53 view = exports.lookup(view, options);5455 // hints56 if (!view.exists) {57 if (options.hint) hintAtViewPaths(view.original, options);58 var err = new Error('failed to locate view "' + view.original.view + '"');59 err.view = view.original;60 throw err;61 } 6263 // compileFixed options.filename, exposing to template enginesTj Holowaychukbefore adoption93189ad
line 64why, one step back64 options.filename = view.path;Merge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e
lines 65–71why, one step back65 view.fn = view.templateEngine.compile(view.contents, options);66 cache[cid] = view;67 68 return view;69};7071/**added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 72–73why, one step back72 * Lookup `view`, returning an instanceof `View`.73 *Updated jade submoduleTj Holowaychukbefore adoptioneeb7754
lines 74–77why, one step back74 * Options:75 *76 * - `root` root directory path77 * - `defaultEngine` default template enginedocsTj Holowaychukbefore adoption8636dee
line 78why, one step back78 * - `parentView` parent `View` objectMerge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e
lines 79–80why, one step back79 * - `cache` cache object80 * - `cacheid` optional cache idUpdated jade submoduleTj Holowaychukbefore adoptioneeb7754
line 81why, one step back81 *lookup docsTj Holowaychukbefore adoption1b199b7
lines 82–89why, one step back82 * Lookup:83 *84 * - partial `_<name>` 85 * - any `<name>/index` 86 * - non-layout `../<name>/index` 87 * - any `<root>/<name>` 88 * - partial `<root>/_<name>` 89 *added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 90–96why, one step back90 * @param {String} view91 * @param {Object} options92 * @return {View}93 * @api private94 */9596exports.lookup = function(view, options){Fixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
lines 97–99why, one step back97 var orig = view = new View(view, options)98 , partial = options.isPartial99 , layout = options.isLayout;added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 100–101why, one step back100101 // Try _ prefix ex: ./views/_<name>.jadeFixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 102why, one step back102 // taking precedence over the direct pathadded exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 103–108why, one step back103 if (partial) {104 view = new View(orig.prefixPath, options);105 if (!view.exists) view = orig;106 }107108 // Try index ex: ./views/user/index.jadeFixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 109why, one step back109 if (!layout && !view.exists) view = new View(orig.indexPath, options);added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 110–112why, one step back110111 // Try ../<name>/index ex: ../user/index.jade112 // when calling partial('user') within the same dirFixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 113why, one step back113 if (!layout && !view.exists) view = new View(orig.upIndexPath, options);added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 114–125why, one step back114115 // Try root ex: <root>/user.jade116 if (!view.exists) view = new View(orig.rootPath, options);117118 // Try root _ prefix ex: <root>/_user.jade119 if (!view.exists && partial) view = new View(view.prefixPath, options);120121 view.original = orig;122 return view;123};124125/**misc refactorTj Holowaychukbefore adoption0477a53
lines 126–168why, one step back126 * Partial render helper.127 *128 * @api private129 */130131function renderPartial(res, view, options, parentLocals, parent){132 var collection, object, locals;133134 if (options) {135 // collection136 if (options.collection) {137 collection = options.collection;138 delete options.collection;139 } else if ('length' in options) {140 collection = options;141 options = {};142 }143144 // locals145 if (options.locals) {146 locals = options.locals;147 delete options.locals;148 }149150 // object151 if ('Object' != options.constructor.name) {152 object = options;153 options = {};154 } else if (undefined != options.object) {155 object = options.object;156 delete options.object;157 }158 } else {159 options = {};160 }161162 // Inherit locals from parent163 union(options, parentLocals);164 165 // Merge locals166 if (locals) merge(options, locals);167168 // Partials dont need layoutsFixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 169why, one step back169 options.isPartial = true;misc refactorTj Holowaychukbefore adoption0477a53
lines 170–257why, one step back170 options.layout = false;171172 // Deduce name from view path173 var name = options.as || partial.resolveObjectName(view);174175 // Render partial176 function render(){177 if (object) {178 if ('string' == typeof name) {179 options[name] = object;180 } else if (name === global) {181 merge(options, object);182 } else {183 options.scope = object;184 }185 }186 return res.render(view, options, null, parent, true);187 }188189 // Collection support190 if (collection) {191 var len = collection.length192 , buf = ''193 , keys194 , key195 , val;196197 options.collectionLength = len;198199 if ('number' == typeof len || Array.isArray(collection)) {200 for (var i = 0; i < len; ++i) {201 val = collection[i];202 options.firstInCollection = i == 0;203 options.indexInCollection = i;204 options.lastInCollection = i == len - 1;205 object = val;206 buf += render();207 } 208 } else {209 keys = Object.keys(collection);210 len = keys.length;211 options.collectionLength = len;212 options.collectionKeys = keys;213 for (var i = 0; i < len; ++i) {214 key = keys[i];215 val = collection[key];216 options.keyInCollection = key;217 options.firstInCollection = i == 0;218 options.indexInCollection = i;219 options.lastInCollection = i == len - 1;220 object = val;221 buf += render();222 }223 }224225 return buf;226 } else {227 return render();228 }229};230231/**232 * Render `view` partial with the given `options`. Optionally a 233 * callback `fn(err, str)` may be passed instead of writing to234 * the socket.235 *236 * Options:237 *238 * - `object` Single object with name derived from the view (unless `as` is present) 239 *240 * - `as` Variable name for each `collection` value, defaults to the view name.241 * * as: 'something' will add the `something` local variable242 * * as: this will use the collection value as the template context243 * * as: global will merge the collection value's properties with `locals`244 *245 * - `collection` Array of objects, the name is derived from the view name itself. 246 * For example _video.html_ will have a object _video_ available to it.247 *248 * @param {String} view249 * @param {Object|Array|Function} options, collection, callback, or object250 * @param {Function} fn251 * @return {String}252 * @api public253 */254255res.partial = function(view, options, fn){256 var app = this.app257 , options = options || {}misc refactor of res.partial()Tj Holowaychukbefore adoption72384b0
line 258why, one step back258 , viewEngine = app.set('view engine')misc refactorTj Holowaychukbefore adoption0477a53
lines 259–270why, one step back259 , parent = {};260261 // accept callback as second argument262 if ('function' == typeof options) {263 fn = options;264 options = {};265 }266267 // root "views" option268 parent.dirname = app.set('views') || process.cwd() + '/views';269270 // utilize "view engine" optionmisc view refactoringTj Holowaychukbefore adoptionf026218
line 271why, one step back271 if (viewEngine) parent.engine = viewEngine;misc refactorTj Holowaychukbefore adoption0477a53
lines 272–321why, one step back272273 // render the partial274 try {275 var str = renderPartial(this, view, options, null, parent);276 } catch (err) {277 if (fn) {278 fn(err);279 } else {280 this.req.next(err);281 }282 return;283 }284285 // callback or transfer286 if (fn) {287 fn(null, str);288 } else {289 this.send(str);290 }291};292293/**294 * Render `view` with the given `options` and optional callback `fn`.295 * When a callback function is given a response will _not_ be made296 * automatically, however otherwise a response of _200_ and _text/html_ is given.297 *298 * Options:299 * 300 * - `scope` Template evaluation context (the value of `this`)301 * - `debug` Output debugging information302 * - `status` Response status code303 *304 * @param {String} view305 * @param {Object|Function} options or callback function306 * @param {Function} fn307 * @api public308 */309310res.render = function(view, opts, fn, parent, sub){311 // support callback function as second arg312 if ('function' == typeof opts) {313 fn = opts, opts = null;314 }315316 try {317 return this._render(view, opts, fn, parent, sub);318 } catch (err) {319 // callback given320 if (fn) {321 fn(err);docsTj Holowaychukbefore adoption4b9cc3d
line 322why, one step back322 // unwind to root call to prevent multiple callbacksmisc refactorTj Holowaychukbefore adoption0477a53
lines 323–340why, one step back323 } else if (sub) {324 throw err;325 // root template, next(err)326 } else {327 this.req.next(err);328 }329 }330};331332// private render()333334res._render = function(view, opts, fn, parent, sub){335 var options = {}336 , self = this337 , app = this.app338 , root = app.set('views') || process.cwd() + '/views';339340 // cache idMerge branch 'refactor/dev-deps'Tj Holowaychukbefore adoption7999386
lines 341–343why, one step back341 var cid = app.enabled('view cache')342 ? view + (parent ? ':' + parent.path : '')343 : false;misc refactorTj Holowaychukbefore adoption0477a53
line 344why, one step back344fixed app.locals precedenceTj Holowaychukbefore adoption509601e
lines 345–347why, one step back345 // merge app.locals346 union(options, app.locals);347Replaced `res.local[s]()` with `res.locals` function. Closes #757Tj Holowaychukbefore adoption9a8b868
lines 348–349why, one step back348 // merge res.locals349 merge(options, this.locals);misc refactorTj Holowaychukbefore adoption0477a53
lines 350–362why, one step back350351 // merge render() options352 if (opts) merge(options, opts);353354 // merge render() .locals355 if (opts && opts.locals) merge(options, opts.locals);356357 // status support358 if (options.status) this.statusCode = options.status;359360 // capture attempts361 options.attempts = [];362Fixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 363why, one step back363 var partial = options.isPartialmisc refactorTj Holowaychukbefore adoption0477a53
lines 364–390why, one step back364 , layout = options.layout;365366 // Layout support367 if (true === layout || undefined === layout) {368 layout = 'layout';369 }370371 // Default execution scope to a plain object372 options.scope = options.scope || {};373374 // Populate view375 options.parentView = parent;376377 // "views" setting378 options.root = root;379380 // "view engine" setting381 options.defaultEngine = app.set('view engine');382383 // charset option384 if (options.charset) this.charset = options.charset;385386 // Always expose partial() as a local387 options.partial = function(path, opts){388 return renderPartial(self, path, opts, options, view);389 };390Merge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e
lines 391–393why, one step back391 // View lookup392 options.hint = app.enabled('hints');393 view = exports.compile(view, app.cache, cid, options);misc refactorTj Holowaychukbefore adoption0477a53
lines 394–436why, one step back394395 // layout helper396 options.layout = function(path){397 layout = path;398 };399400 // render401 var str = view.fn.call(options.scope, options);402403 // layout expected404 if (layout) {405 options.isLayout = true;406 options.layout = false;407 options.body = str;408 this.render(layout, options, fn, view, true);409 // partial return410 } else if (partial) {411 return str;412 // render complete, and 413 // callback given414 } else if (fn) {415 fn(null, str);416 // respond417 } else {418 this.send(str);419 }420}421422/**423 * Hint at view path resolution, outputting the424 * paths that Express has tried.425 *426 * @api private427 */428429function hintAtViewPaths(view, options) {430 console.error();431 console.error('failed to locate view "' + view.view + '", tried:');432 options.attempts.forEach(function(path){433 console.error(' - %s', path);434 });435 console.error();436}