view.js
This file
Path
lib/view.js
459 lines · 10.6 KiB · JavaScript
Last changed by
docsTj Holowaychukbefore adoption4b9cc3d
History of this fileTake it
The walk stopped after 200 commits: lines older than fb38d9c point at it.
add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
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–70why, 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 // compile64 view.fn = view.templateEngine.compile(view.contents, options);65 cache[cid] = view;66 67 return view;68};6970/**added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 71–72why, one step back71 * Lookup `view`, returning an instanceof `View`.72 *Updated jade submoduleTj Holowaychukbefore adoptioneeb7754
lines 73–76why, one step back73 * Options:74 *75 * - `root` root directory path76 * - `defaultEngine` default template enginedocsTj Holowaychukbefore adoption8636dee
line 77why, one step back77 * - `parentView` parent `View` objectMerge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e
lines 78–79why, one step back78 * - `cache` cache object79 * - `cacheid` optional cache idUpdated jade submoduleTj Holowaychukbefore adoptioneeb7754
line 80why, one step back80 *lookup docsTj Holowaychukbefore adoption1b199b7
lines 81–88why, one step back81 * Lookup:82 *83 * - partial `_<name>` 84 * - any `<name>/index` 85 * - non-layout `../<name>/index` 86 * - any `<root>/<name>` 87 * - partial `<root>/_<name>` 88 *added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 89–95why, one step back89 * @param {String} view90 * @param {Object} options91 * @return {View}92 * @api private93 */9495exports.lookup = function(view, options){Fixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
lines 96–98why, one step back96 var orig = view = new View(view, options)97 , partial = options.isPartial98 , layout = options.isLayout;added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 99–100why, one step back99100 // Try _ prefix ex: ./views/_<name>.jadeFixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 101why, one step back101 // taking precedence over the direct pathadded exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 102–107why, one step back102 if (partial) {103 view = new View(orig.prefixPath, options);104 if (!view.exists) view = orig;105 }106107 // Try index ex: ./views/user/index.jadeFixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 108why, one step back108 if (!layout && !view.exists) view = new View(orig.indexPath, options);added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 109–111why, one step back109110 // Try ../<name>/index ex: ../user/index.jade111 // when calling partial('user') within the same dirFixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 112why, one step back112 if (!layout && !view.exists) view = new View(orig.upIndexPath, options);added exports.lookup(view, options) to view.jsTj Holowaychukbefore adoption3043672
lines 113–124why, one step back113114 // Try root ex: <root>/user.jade115 if (!view.exists) view = new View(orig.rootPath, options);116117 // Try root _ prefix ex: <root>/_user.jade118 if (!view.exists && partial) view = new View(view.prefixPath, options);119120 view.original = orig;121 return view;122};123124/**add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 125–167why, one step back125 * Partial render helper.126 *127 * @api private128 */129130function renderPartial(res, view, options, parentLocals, parent){131 var collection, object, locals;132133 if (options) {134 // collection135 if (options.collection) {136 collection = options.collection;137 delete options.collection;138 } else if ('length' in options) {139 collection = options;140 options = {};141 }142143 // locals144 if (options.locals) {145 locals = options.locals;146 delete options.locals;147 }148149 // object150 if ('Object' != options.constructor.name) {151 object = options;152 options = {};153 } else if (undefined != options.object) {154 object = options.object;155 delete options.object;156 }157 } else {158 options = {};159 }160161 // Inherit locals from parent162 union(options, parentLocals);163 164 // Merge locals165 if (locals) merge(options, locals);166167 // Partials dont need layoutsFixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 168why, one step back168 options.isPartial = true;add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 169–190why, one step back169 options.layout = false;170171 // Deduce name from view path172 var name = options.as || partial.resolveObjectName(view);173174 // Render partial175 function render(){176 if (object) {177 if ('string' == typeof name) {178 options[name] = object;179 } else if (name === global) {180 merge(options, object);181 } else {182 options.scope = object;183 }184 }185 return res.render(view, options, null, parent, true);186 }187188 // Collection support189 if (collection) {190 var len = collection.lengthAdded better partial() object collection supportTj Holowaychukbefore adoption08046f7
lines 191–195why, one step back191 , buf = ''192 , keys193 , key194 , val;195add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
line 196why, one step back196 options.collectionLength = len;Added better partial() object collection supportTj Holowaychukbefore adoption08046f7
lines 197–214why, one step back197198 if ('number' == typeof len || Array.isArray(collection)) {199 for (var i = 0; i < len; ++i) {200 val = collection[i];201 options.firstInCollection = i == 0;202 options.indexInCollection = i;203 options.lastInCollection = i == len - 1;204 object = val;205 buf += render();206 } 207 } else {208 keys = Object.keys(collection);209 len = keys.length;210 options.collectionLength = len;211 options.collectionKeys = keys;212 for (var i = 0; i < len; ++i) {213 key = keys[i];214 val = collection[key];misc refactoringTj Holowaychukbefore adoption89383ec
line 215why, one step back215 options.keyInCollection = key;Added better partial() object collection supportTj Holowaychukbefore adoption08046f7
lines 216–221why, one step back216 options.firstInCollection = i == 0;217 options.indexInCollection = i;218 options.lastInCollection = i == len - 1;219 object = val;220 buf += render();221 }add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
line 222why, one step back222 }Added better partial() object collection supportTj Holowaychukbefore adoption08046f7
line 223why, one step back223add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 224–256why, one step back224 return buf;225 } else {226 return render();227 }228};229230/**231 * Render `view` partial with the given `options`. Optionally a 232 * callback `fn(err, str)` may be passed instead of writing to233 * the socket.234 *235 * Options:236 *237 * - `object` Single object with name derived from the view (unless `as` is present) 238 *239 * - `as` Variable name for each `collection` value, defaults to the view name.240 * * as: 'something' will add the `something` local variable241 * * as: this will use the collection value as the template context242 * * as: global will merge the collection value's properties with `locals`243 *244 * - `collection` Array of objects, the name is derived from the view name itself. 245 * For example _video.html_ will have a object _video_ available to it.246 *247 * @param {String} view248 * @param {Object|Array|Function} options, collection, callback, or object249 * @param {Function} fn250 * @return {String}251 * @api public252 */253254res.partial = function(view, options, fn){255 var app = this.app256 , options = options || {}misc refactor of res.partial()Tj Holowaychukbefore adoption72384b0
line 257why, one step back257 , viewEngine = app.set('view engine')add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 258–269why, one step back258 , parent = {};259260 // accept callback as second argument261 if ('function' == typeof options) {262 fn = options;263 options = {};264 }265266 // root "views" option267 parent.dirname = app.set('views') || process.cwd() + '/views';268269 // utilize "view engine" optionmisc view refactoringTj Holowaychukbefore adoptionf026218
line 270why, one step back270 if (viewEngine) parent.engine = viewEngine;add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 271–278why, one step back271272 // render the partial273 try {274 var str = renderPartial(this, view, options, null, parent);275 } catch (err) {276 if (fn) {277 fn(err);278 } else {Fixed res.partial(); next(err) when no callback is given [reported by aheckmann]Tj Holowaychukbefore adoption28ba9e8
line 279why, one step back279 this.req.next(err);add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
line 280why, one step back280 }Fixed res.partial(); next(err) when no callback is given [reported by aheckmann]Tj Holowaychukbefore adoption28ba9e8
line 281why, one step back281 return;add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 282–320why, one step back282 }283284 // callback or transfer285 if (fn) {286 fn(null, str);287 } else {288 this.send(str);289 }290};291292/**293 * Render `view` with the given `options` and optional callback `fn`.294 * When a callback function is given a response will _not_ be made295 * automatically, however otherwise a response of _200_ and _text/html_ is given.296 *297 * Options:298 * 299 * - `scope` Template evaluation context (the value of `this`)300 * - `debug` Output debugging information301 * - `status` Response status code302 *303 * @param {String} view304 * @param {Object|Function} options or callback function305 * @param {Function} fn306 * @api public307 */308309res.render = function(view, opts, fn, parent, sub){310 // support callback function as second arg311 if ('function' == typeof opts) {312 fn = opts, opts = null;313 }314315 try {316 return this._render(view, opts, fn, parent, sub);317 } catch (err) {318 // callback given319 if (fn) {320 fn(err);docsTj Holowaychukbefore adoption4b9cc3d
line 321why, one step back321 // unwind to root call to prevent multiple callbacksadd test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 322–336why, one step back322 } else if (sub) {323 throw err;324 // root template, next(err)325 } else {326 this.req.next(err);327 }328 }329};330331// private render()332333res._render = function(view, opts, fn, parent, sub){334 var options = {}335 , self = this336 , app = this.appviewHelpers -> _localsTj Holowaychukbefore adoptioneac6665
line 337why, one step back337 , helpers = app._localsadd test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 338–339why, one step back338 , dynamicHelpers = app.dynamicViewHelpers339 , viewOptions = app.set('view options')misc refactoringTj Holowaychukbefore adoption11250d2
line 340why, one step back340 , root = app.set('views') || process.cwd() + '/views';add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
line 341why, one step back341Fixed template caching collision issue. Closes #644Tj Holowaychukbefore adoption470774c
line 342why, one step back342 // cache idMerge branch 'refactor/dev-deps'Tj Holowaychukbefore adoption7999386
lines 343–345why, one step back343 var cid = app.enabled('view cache')344 ? view + (parent ? ':' + parent.path : '')345 : false;Fixed template caching collision issue. Closes #644Tj Holowaychukbefore adoption470774c
line 346why, one step back346add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 347–361why, one step back347 // merge "view options"348 if (viewOptions) merge(options, viewOptions);349350 // merge res._locals351 if (this._locals) merge(options, this._locals);352353 // merge render() options354 if (opts) merge(options, opts);355356 // merge render() .locals357 if (opts && opts.locals) merge(options, opts.locals);358359 // status support360 if (options.status) this.statusCode = options.status;361Fixed view hintsTj Holowaychukbefore adoptionae10789
lines 362–364why, one step back362 // capture attempts363 options.attempts = [];364Fixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 365why, one step back365 var partial = options.isPartialadd test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 366–412why, one step back366 , layout = options.layout;367368 // Layout support369 if (true === layout || undefined === layout) {370 layout = 'layout';371 }372373 // Default execution scope to a plain object374 options.scope = options.scope || {};375376 // Populate view377 options.parentView = parent;378379 // "views" setting380 options.root = root;381382 // "view engine" setting383 options.defaultEngine = app.set('view engine');384385 // charset option386 if (options.charset) this.charset = options.charset;387388 // Dynamic helper support389 if (false !== options.dynamicHelpers) {390 // cache391 if (!this.__dynamicHelpers) {392 this.__dynamicHelpers = {};393 for (var key in dynamicHelpers) {394 this.__dynamicHelpers[key] = dynamicHelpers[key].call(395 this.app396 , this.req397 , this);398 }399 }400401 // apply402 merge(options, this.__dynamicHelpers);403 }404405 // Merge view helpers406 union(options, helpers);407408 // Always expose partial() as a local409 options.partial = function(path, opts){410 return renderPartial(self, path, opts, options, view);411 };412Merge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e
lines 413–416why, one step back413 // View lookup414 options.hint = app.enabled('hints');415 view = exports.compile(view, app.cache, cid, options);416 options.filename = view.path;Performance improved with better view cachingTj Holowaychukbefore adoption4b4de29
line 417why, one step back417Merge branch 'feature/view-layout-control'Tj Holowaychukbefore adoption6a58c71
lines 418–422why, one step back418 // layout helper419 options.layout = function(path){420 layout = path;421 };422Performance improved with better view cachingTj Holowaychukbefore adoption4b4de29
lines 423–424why, one step back423 // render424 var str = view.fn.call(options.scope, options);add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 425–454why, one step back425426 // layout expected427 if (layout) {428 options.isLayout = true;429 options.layout = false;430 options.body = str;431 this.render(layout, options, fn, view, true);432 // partial return433 } else if (partial) {434 return str;435 // render complete, and 436 // callback given437 } else if (fn) {438 fn(null, str);439 // respond440 } else {441 this.send(str);442 }443}444445/**446 * Hint at view path resolution, outputting the447 * paths that Express has tried.448 *449 * @api private450 */451452function hintAtViewPaths(view, options) {453 console.error();454 console.error('failed to locate view "' + view.view + '", tried:');Fixed view hintsTj Holowaychukbefore adoptionae10789
lines 455–457why, one step back455 options.attempts.forEach(function(path){456 console.error(' - %s', path);457 });add test for res.send(undefined)Aaron Heckmannbefore adoptionfb38d9c
lines 458–459why, one step back458 console.error();459}