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
12/*!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/**37 * 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 options.filename = view.path;65 view.fn = view.templateEngine.compile(view.contents, options);66 cache[cid] = view;67 68 return view;69};7071/**72 * Lookup `view`, returning an instanceof `View`.73 *74 * Options:75 *76 * - `root` root directory path77 * - `defaultEngine` default template engine78 * - `parentView` parent `View` object79 * - `cache` cache object80 * - `cacheid` optional cache id81 *82 * Lookup:83 *84 * - partial `_<name>` 85 * - any `<name>/index` 86 * - non-layout `../<name>/index` 87 * - any `<root>/<name>` 88 * - partial `<root>/_<name>` 89 *90 * @param {String} view91 * @param {Object} options92 * @return {View}93 * @api private94 */9596exports.lookup = function(view, options){97 var orig = view = new View(view, options)98 , partial = options.isPartial99 , layout = options.isLayout;100101 // Try _ prefix ex: ./views/_<name>.jade102 // taking precedence over the direct path103 if (partial) {104 view = new View(orig.prefixPath, options);105 if (!view.exists) view = orig;106 }107108 // Try index ex: ./views/user/index.jade109 if (!layout && !view.exists) view = new View(orig.indexPath, options);110111 // Try ../<name>/index ex: ../user/index.jade112 // when calling partial('user') within the same dir113 if (!layout && !view.exists) view = new View(orig.upIndexPath, options);114115 // 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/**126 * 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 layouts169 options.isPartial = true;170 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 || {}258 , viewEngine = app.set('view engine')259 , 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" option271 if (viewEngine) parent.engine = viewEngine;272273 // 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);322 // unwind to root call to prevent multiple callbacks323 } 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 , locals = app.locals339 , dynamic = app._dynamicLocals340 , root = app.set('views') || process.cwd() + '/views';341342 // cache id343 var cid = app.enabled('view cache')344 ? view + (parent ? ':' + parent.path : '')345 : false;346347 // merge res.locals348 merge(options, this.locals);349350 // 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;358359 // capture attempts360 options.attempts = [];361362 var partial = options.isPartial363 , 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;384385 // Merge view locals386 union(options, locals);387388 // Always expose partial() as a local389 options.partial = function(path, opts){390 return renderPartial(self, path, opts, options, view);391 };392393 // View lookup394 options.hint = app.enabled('hints');395 view = exports.compile(view, app.cache, cid, options);396397 // 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:');434 options.attempts.forEach(function(path){435 console.error(' - %s', path);436 });437 console.error();438}