Skip to content
Myr

view.js

This file

Path

lib/view.js

457 lines · 10.5 KiB · JavaScript

Last changed by

misc view refactoringTj Holowaychukbefore adoptionf026218

History of this file

Take it

The walk stopped after 200 commits: lines older than cf26cf7 point at it.

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 1–36why, one step back
1
2/*!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 back
37 * Lookup and compile `view` with cache support by supplying
38 * 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 back
71 * Lookup `view`, returning an instanceof `View`.
72 *

Updated jade submoduleTj Holowaychukbefore adoptioneeb7754

lines 73–76why, one step back
73 * Options:
74 *75 * - `root` root directory path76 * - `defaultEngine` default template engine

docsTj Holowaychukbefore adoption8636dee

line 77why, one step back
77 * - `parentView` parent `View` object

Merge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e

lines 78–79why, one step back
78 * - `cache` cache object
79 * - `cacheid` optional cache id

Updated jade submoduleTj Holowaychukbefore adoptioneeb7754

line 80why, one step back
80 *

lookup docsTj Holowaychukbefore adoption1b199b7

lines 81–88why, one step back
81 * 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–121why, one step back
89 * @param {String} view
90 * @param {Object} options91 * @return {View}92 * @api private93 */9495exports.lookup = function(view, options){96 var orig = view = new View(view, options);9798 // Try _ prefix ex: ./views/_<name>.jade99 if (partial) {100 view = new View(orig.prefixPath, options);101 if (!view.exists) view = orig;102 }103104 // Try index ex: ./views/user/index.jade105 if (!view.exists) view = new View(orig.indexPath, options);106107 // Try ../<name>/index ex: ../user/index.jade108 // when calling partial('user') within the same dir109 if (!view.exists && !options.isLayout) view = new View(orig.upIndexPath, options);110111 // Try root ex: <root>/user.jade112 if (!view.exists) view = new View(orig.rootPath, options);113114 // Try root _ prefix ex: <root>/_user.jade115 if (!view.exists && partial) view = new View(view.prefixPath, options);116117 view.original = orig;118 return view;119};120121/**

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 122–187why, one step back
122 * Partial render helper.
123 *124 * @api private125 */126127function renderPartial(res, view, options, parentLocals, parent){128 var collection, object, locals;129130 if (options) {131 // collection132 if (options.collection) {133 collection = options.collection;134 delete options.collection;135 } else if ('length' in options) {136 collection = options;137 options = {};138 }139140 // locals141 if (options.locals) {142 locals = options.locals;143 delete options.locals;144 }145146 // object147 if ('Object' != options.constructor.name) {148 object = options;149 options = {};150 } else if (undefined != options.object) {151 object = options.object;152 delete options.object;153 }154 } else {155 options = {};156 }157158 // Inherit locals from parent159 union(options, parentLocals);160 161 // Merge locals162 if (locals) merge(options, locals);163164 // Partials dont need layouts165 options.renderPartial = true;166 options.layout = false;167168 // Deduce name from view path169 var name = options.as || partial.resolveObjectName(view);170171 // Render partial172 function render(){173 if (object) {174 if ('string' == typeof name) {175 options[name] = object;176 } else if (name === global) {177 merge(options, object);178 } else {179 options.scope = object;180 }181 }182 return res.render(view, options, null, parent, true);183 }184185 // Collection support186 if (collection) {187 var len = collection.length

Added better partial() object collection supportTj Holowaychukbefore adoption08046f7

lines 188–192why, one step back
188 , buf = ''
189 , keys190 , key191 , val;192

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

line 193why, one step back
193 options.collectionLength = len;

Added better partial() object collection supportTj Holowaychukbefore adoption08046f7

lines 194–211why, one step back
194
195 if ('number' == typeof len || Array.isArray(collection)) {196 for (var i = 0; i < len; ++i) {197 val = collection[i];198 options.firstInCollection = i == 0;199 options.indexInCollection = i;200 options.lastInCollection = i == len - 1;201 object = val;202 buf += render();203 } 204 } else {205 keys = Object.keys(collection);206 len = keys.length;207 options.collectionLength = len;208 options.collectionKeys = keys;209 for (var i = 0; i < len; ++i) {210 key = keys[i];211 val = collection[key];

misc refactoringTj Holowaychukbefore adoption89383ec

line 212why, one step back
212 options.keyInCollection = key;

Added better partial() object collection supportTj Holowaychukbefore adoption08046f7

lines 213–218why, one step back
213 options.firstInCollection = i == 0;
214 options.indexInCollection = i;215 options.lastInCollection = i == len - 1;216 object = val;217 buf += render();218 }

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

line 219why, one step back
219 }

Added better partial() object collection supportTj Holowaychukbefore adoption08046f7

line 220why, one step back
220

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 221–253why, one step back
221 return buf;
222 } else {223 return render();224 }225};226227/**228 * Render `view` partial with the given `options`. Optionally a 229 * callback `fn(err, str)` may be passed instead of writing to230 * the socket.231 *232 * Options:233 *234 * - `object` Single object with name derived from the view (unless `as` is present) 235 *236 * - `as` Variable name for each `collection` value, defaults to the view name.237 * * as: 'something' will add the `something` local variable238 * * as: this will use the collection value as the template context239 * * as: global will merge the collection value's properties with `locals`240 *241 * - `collection` Array of objects, the name is derived from the view name itself. 242 * For example _video.html_ will have a object _video_ available to it.243 *244 * @param {String} view245 * @param {Object|Array|Function} options, collection, callback, or object246 * @param {Function} fn247 * @return {String}248 * @api public249 */250251res.partial = function(view, options, fn){252 var app = this.app253 , options = options || {}

misc refactor of res.partial()Tj Holowaychukbefore adoption72384b0

line 254why, one step back
254 , viewEngine = app.set('view engine')

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 255–266why, one step back
255 , parent = {};
256257 // accept callback as second argument258 if ('function' == typeof options) {259 fn = options;260 options = {};261 }262263 // root "views" option264 parent.dirname = app.set('views') || process.cwd() + '/views';265266 // utilize "view engine" option

misc view refactoringTj Holowaychukbefore adoptionf026218

line 267why, one step back
267 if (viewEngine) parent.engine = viewEngine;

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 268–275why, one step back
268
269 // render the partial270 try {271 var str = renderPartial(this, view, options, null, parent);272 } catch (err) {273 if (fn) {274 fn(err);275 } else {

Fixed res.partial(); next(err) when no callback is given [reported by aheckmann]Tj Holowaychukbefore adoption28ba9e8

line 276why, one step back
276 this.req.next(err);

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

line 277why, one step back
277 }

Fixed res.partial(); next(err) when no callback is given [reported by aheckmann]Tj Holowaychukbefore adoption28ba9e8

line 278why, one step back
278 return;

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 279–317why, one step back
279 }
280281 // callback or transfer282 if (fn) {283 fn(null, str);284 } else {285 this.send(str);286 }287};288289/**290 * Render `view` with the given `options` and optional callback `fn`.291 * When a callback function is given a response will _not_ be made292 * automatically, however otherwise a response of _200_ and _text/html_ is given.293 *294 * Options:295 * 296 * - `scope` Template evaluation context (the value of `this`)297 * - `debug` Output debugging information298 * - `status` Response status code299 *300 * @param {String} view301 * @param {Object|Function} options or callback function302 * @param {Function} fn303 * @api public304 */305306res.render = function(view, opts, fn, parent, sub){307 // support callback function as second arg308 if ('function' == typeof opts) {309 fn = opts, opts = null;310 }311312 try {313 return this._render(view, opts, fn, parent, sub);314 } catch (err) {315 // callback given316 if (fn) {317 fn(err);

docsTj Holowaychukbefore adoption7888cb0

lines 318–319why, one step back
318 // unwind to root call to prevent
319 // several next(err) calls

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 320–334why, one step back
320 } else if (sub) {
321 throw err;322 // root template, next(err)323 } else {324 this.req.next(err);325 }326 }327};328329// private render()330331res._render = function(view, opts, fn, parent, sub){332 var options = {}333 , self = this334 , app = this.app

viewHelpers -> _localsTj Holowaychukbefore adoptioneac6665

line 335why, one step back
335 , helpers = app._locals

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 336–337why, one step back
336 , dynamicHelpers = app.dynamicViewHelpers
337 , viewOptions = app.set('view options')

misc refactoringTj Holowaychukbefore adoption11250d2

line 338why, one step back
338 , root = app.set('views') || process.cwd() + '/views';

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

line 339why, one step back
339

Fixed template caching collision issue. Closes #644Tj Holowaychukbefore adoption470774c

line 340why, one step back
340 // cache id

Merge branch 'refactor/dev-deps'Tj Holowaychukbefore adoption7999386

lines 341–343why, one step back
341 var cid = app.enabled('view cache')
342 ? view + (parent ? ':' + parent.path : '')343 : false;

Fixed template caching collision issue. Closes #644Tj Holowaychukbefore adoption470774c

line 344why, one step back
344

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 345–359why, one step back
345 // merge "view options"
346 if (viewOptions) merge(options, viewOptions);347348 // merge res._locals349 if (this._locals) merge(options, this._locals);350351 // 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;359

Fixed view hintsTj Holowaychukbefore adoptionae10789

lines 360–362why, one step back
360 // capture attempts
361 options.attempts = [];362

misc refactoringTj Holowaychukbefore adoption11250d2

line 363why, one step back
363 var partial = options.renderPartial

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 364–410why, one step back
364 , 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 // Dynamic helper support387 if (false !== options.dynamicHelpers) {388 // cache389 if (!this.__dynamicHelpers) {390 this.__dynamicHelpers = {};391 for (var key in dynamicHelpers) {392 this.__dynamicHelpers[key] = dynamicHelpers[key].call(393 this.app394 , this.req395 , this);396 }397 }398399 // apply400 merge(options, this.__dynamicHelpers);401 }402403 // Merge view helpers404 union(options, helpers);405406 // Always expose partial() as a local407 options.partial = function(path, opts){408 return renderPartial(self, path, opts, options, view);409 };410

Merge branch 'refactor/views'Tj Holowaychukbefore adoption09b384e

lines 411–414why, one step back
411 // View lookup
412 options.hint = app.enabled('hints');413 view = exports.compile(view, app.cache, cid, options);414 options.filename = view.path;

Performance improved with better view cachingTj Holowaychukbefore adoption4b4de29

line 415why, one step back
415

Merge branch 'feature/view-layout-control'Tj Holowaychukbefore adoption6a58c71

lines 416–420why, one step back
416 // layout helper
417 options.layout = function(path){418 layout = path;419 };420

Performance improved with better view cachingTj Holowaychukbefore adoption4b4de29

lines 421–422why, one step back
421 // render
422 var str = view.fn.call(options.scope, options);

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 423–452why, one step back
423
424 // layout expected425 if (layout) {426 options.isLayout = true;427 options.layout = false;428 options.body = str;429 this.render(layout, options, fn, view, true);430 // partial return431 } else if (partial) {432 return str;433 // render complete, and 434 // callback given435 } else if (fn) {436 fn(null, str);437 // respond438 } else {439 this.send(str);440 }441}442443/**444 * Hint at view path resolution, outputting the445 * paths that Express has tried.446 *447 * @api private448 */449450function hintAtViewPaths(view, options) {451 console.error();452 console.error('failed to locate view "' + view.view + '", tried:');

Fixed view hintsTj Holowaychukbefore adoptionae10789

lines 453–455why, one step back
453 options.attempts.forEach(function(path){
454 console.error(' - %s', path);455 });

wrap try/catch around render()Tj Holowaychukbefore adoptioncf26cf7

lines 456–457why, one step back
456 console.error();
457}