view.js
This file
Path
lib/view.js
438 lines · 10.0 KiB · JavaScript
Last changed by
removed old dynamic helper logic from the view systemTj Holowaychukbefore adoption986916c
History of this fileTake it
The walk stopped after 200 commits: lines older than 759a57b point at it.
Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
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/**Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
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;Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
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')Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
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;Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
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 callbacksAdded second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 323–337why, 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.appview system utilizing `app.locals`Tj Holowaychukbefore adoption8c56df7
line 338why, one step back338 , locals = app.locals`app.dynamicHelpers` -> `app.dynamicLocals`Tj Holowaychukbefore adoption0815921
line 339why, one step back339 , dynamic = app._dynamicLocalsAdded second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 340–341why, one step back340 , root = app.set('views') || process.cwd() + '/views';341Fixed 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;Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 346why, one step back346Replaced `res.local[s]()` with `res.locals` function. Closes #757Tj Holowaychukbefore adoption9a8b868
lines 347–348why, one step back347 // merge res.locals348 merge(options, this.locals);Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 349–358why, one step back349350 // merge render() options351 if (opts) merge(options, opts);352353 // merge render() .locals354 if (opts && opts.locals) merge(options, opts.locals);355356 // status support357 if (options.status) this.statusCode = options.status;358Fixed view hintsTj Holowaychukbefore adoptionae10789
lines 359–361why, one step back359 // capture attempts360 options.attempts = [];361Fixed view layout bug. Closes #720Tj Holowaychukbefore adoption0db7f26
line 362why, one step back362 var partial = options.isPartialAdded second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 363–384why, one step back363 , layout = options.layout;364365 // Layout support366 if (true === layout || undefined === layout) {367 layout = 'layout';368 }369370 // Default execution scope to a plain object371 options.scope = options.scope || {};372373 // Populate view374 options.parentView = parent;375376 // "views" setting377 options.root = root;378379 // "view engine" setting380 options.defaultEngine = app.set('view engine');381382 // charset option383 if (options.charset) this.charset = options.charset;384misc refactoringTj Holowaychukbefore adoptionb30efe4
lines 385–386why, one step back385 // Merge view locals386 union(options, locals);Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 387–392why, one step back387388 // Always expose partial() as a local389 options.partial = function(path, opts){390 return renderPartial(self, path, opts, options, view);391 };392Merge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e
lines 393–395why, one step back393 // View lookup394 options.hint = app.enabled('hints');395 view = exports.compile(view, app.cache, cid, options);Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 396–433why, one step back396397 // layout helper398 options.layout = function(path){399 layout = path;400 };401402 // render403 var str = view.fn.call(options.scope, options);404405 // layout expected406 if (layout) {407 options.isLayout = true;408 options.layout = false;409 options.body = str;410 this.render(layout, options, fn, view, true);411 // partial return412 } else if (partial) {413 return str;414 // render complete, and 415 // callback given416 } else if (fn) {417 fn(null, str);418 // respond419 } else {420 this.send(str);421 }422}423424/**425 * Hint at view path resolution, outputting the426 * paths that Express has tried.427 *428 * @api private429 */430431function hintAtViewPaths(view, options) {432 console.error();433 console.error('failed to locate view "' + view.view + '", tried:');Fixed view hintsTj Holowaychukbefore adoptionae10789
lines 434–436why, one step back434 options.attempts.forEach(function(path){435 console.error(' - %s', path);436 });Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 437–438why, one step back437 console.error();438}