view.js
This file
Path
lib/view.js
461 lines · 10.6 KiB · JavaScript
Last changed by
misc refactor of res.partial()Tj Holowaychukbefore adoption72384b0
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 view.fn = view.templateEngine.compile(view.contents, options);65 cache[cid] = view;66 67 return view;68};6970/**71 * Lookup `view`, returning an instanceof `View`.72 *73 * Options:74 *75 * - `root` root directory path76 * - `defaultEngine` default template engine77 * - `parentView` parent `View` object78 * - `cache` cache object79 * - `cacheid` optional cache id80 *81 * Lookup:82 *83 * - partial `_<name>` 84 * - any `<name>/index` 85 * - non-layout `../<name>/index` 86 * - any `<root>/<name>` 87 * - partial `<root>/_<name>` 88 *89 * @param {String} view90 * @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/**122 * Partial render helper.123 *124 * @api private125 */126127function renderPartial(res, view, options, parentLocals, parent){128 var collection, object, locals;129130 // Inherit parent view extension when not present131 if (parent && !~view.indexOf('.')) {132 view += parent.extension;133 }134135 if (options) {136 // collection137 if (options.collection) {138 collection = options.collection;139 delete options.collection;140 } else if ('length' in options) {141 collection = options;142 options = {};143 }144145 // locals146 if (options.locals) {147 locals = options.locals;148 delete options.locals;149 }150151 // object152 if ('Object' != options.constructor.name) {153 object = options;154 options = {};155 } else if (undefined != options.object) {156 object = options.object;157 delete options.object;158 }159 } else {160 options = {};161 }162163 // Inherit locals from parent164 union(options, parentLocals);165 166 // Merge locals167 if (locals) merge(options, locals);168169 // Partials dont need layouts170 options.renderPartial = true;171 options.layout = false;172173 // Deduce name from view path174 var name = options.as || partial.resolveObjectName(view);175176 // Render partial177 function render(){178 if (object) {179 if ('string' == typeof name) {180 options[name] = object;181 } else if (name === global) {182 merge(options, object);183 } else {184 options.scope = object;185 }186 }187 return res.render(view, options, null, parent, true);188 }189190 // Collection support191 if (collection) {192 var len = collection.length193 , buf = ''194 , keys195 , key196 , val;197198 options.collectionLength = len;199200 if ('number' == typeof len || Array.isArray(collection)) {201 for (var i = 0; i < len; ++i) {202 val = collection[i];203 options.firstInCollection = i == 0;204 options.indexInCollection = i;205 options.lastInCollection = i == len - 1;206 object = val;207 buf += render();208 } 209 } else {210 keys = Object.keys(collection);211 len = keys.length;212 options.collectionLength = len;213 options.collectionKeys = keys;214 for (var i = 0; i < len; ++i) {215 key = keys[i];216 val = collection[key];217 options.keyInCollection = key;218 options.firstInCollection = i == 0;219 options.indexInCollection = i;220 options.lastInCollection = i == len - 1;221 object = val;222 buf += render();223 }224 }225226 return buf;227 } else {228 return render();229 }230};231232/**233 * Render `view` partial with the given `options`. Optionally a 234 * callback `fn(err, str)` may be passed instead of writing to235 * the socket.236 *237 * Options:238 *239 * - `object` Single object with name derived from the view (unless `as` is present) 240 *241 * - `as` Variable name for each `collection` value, defaults to the view name.242 * * as: 'something' will add the `something` local variable243 * * as: this will use the collection value as the template context244 * * as: global will merge the collection value's properties with `locals`245 *246 * - `collection` Array of objects, the name is derived from the view name itself. 247 * For example _video.html_ will have a object _video_ available to it.248 *249 * @param {String} view250 * @param {Object|Array|Function} options, collection, callback, or object251 * @param {Function} fn252 * @return {String}253 * @api public254 */255256res.partial = function(view, options, fn){257 var app = this.app258 , options = options || {}259 , viewEngine = app.set('view engine')260 , parent = {};261262 // accept callback as second argument263 if ('function' == typeof options) {264 fn = options;265 options = {};266 }267268 // root "views" option269 parent.dirname = app.set('views') || process.cwd() + '/views';270271 // utilize "view engine" option272 if (viewEngine) parent.extension = '.' + viewEngine;273274 // render the partial275 try {276 var str = renderPartial(this, view, options, null, parent);277 } catch (err) {278 if (fn) {279 fn(err);280 } else {281 this.req.next(err);282 }283 return;284 }285286 // callback or transfer287 if (fn) {288 fn(null, str);289 } else {290 this.send(str);291 }292};293294/**295 * Render `view` with the given `options` and optional callback `fn`.296 * When a callback function is given a response will _not_ be made297 * automatically, however otherwise a response of _200_ and _text/html_ is given.298 *299 * Options:300 * 301 * - `scope` Template evaluation context (the value of `this`)302 * - `debug` Output debugging information303 * - `status` Response status code304 *305 * @param {String} view306 * @param {Object|Function} options or callback function307 * @param {Function} fn308 * @api public309 */310311res.render = function(view, opts, fn, parent, sub){312 // support callback function as second arg313 if ('function' == typeof opts) {314 fn = opts, opts = null;315 }316317 try {318 return this._render(view, opts, fn, parent, sub);319 } catch (err) {320 // callback given321 if (fn) {322 fn(err);323 // unwind to root call to prevent324 // several next(err) calls325 } else if (sub) {326 throw err;327 // root template, next(err)328 } else {329 this.req.next(err);330 }331 }332};333334// private render()335336res._render = function(view, opts, fn, parent, sub){337 var options = {}338 , self = this339 , app = this.app340 , helpers = app._locals341 , dynamicHelpers = app.dynamicViewHelpers342 , viewOptions = app.set('view options')343 , cacheViews = app.enabled('view cache')344 , root = app.set('views') || process.cwd() + '/views';345346 // cache id347 var cid = view + (parent ? ':' + parent.path : '');348349 // merge "view options"350 if (viewOptions) merge(options, viewOptions);351352 // merge res._locals353 if (this._locals) merge(options, this._locals);354355 // merge render() options356 if (opts) merge(options, opts);357358 // merge render() .locals359 if (opts && opts.locals) merge(options, opts.locals);360361 // status support362 if (options.status) this.statusCode = options.status;363364 // capture attempts365 options.attempts = [];366367 var partial = options.renderPartial368 , layout = options.layout;369370 // Layout support371 if (true === layout || undefined === layout) {372 layout = 'layout';373 }374375 // Default execution scope to a plain object376 options.scope = options.scope || {};377378 // Populate view379 options.parentView = parent;380381 // "views" setting382 options.root = root;383384 // "view engine" setting385 options.defaultEngine = app.set('view engine');386387 // charset option388 if (options.charset) this.charset = options.charset;389390 // Dynamic helper support391 if (false !== options.dynamicHelpers) {392 // cache393 if (!this.__dynamicHelpers) {394 this.__dynamicHelpers = {};395 for (var key in dynamicHelpers) {396 this.__dynamicHelpers[key] = dynamicHelpers[key].call(397 this.app398 , this.req399 , this);400 }401 }402403 // apply404 merge(options, this.__dynamicHelpers);405 }406407 // Merge view helpers408 union(options, helpers);409410 // Always expose partial() as a local411 options.partial = function(path, opts){412 return renderPartial(self, path, opts, options, view);413 };414415 // View lookup416 options.hint = app.enabled('hints');417 view = exports.compile(view, app.cache, cid, options);418 options.filename = view.path;419420 // layout helper421 options.layout = function(path){422 layout = path;423 };424425 // render426 var str = view.fn.call(options.scope, options);427428 // layout expected429 if (layout) {430 options.isLayout = true;431 options.layout = false;432 options.body = str;433 this.render(layout, options, fn, view, true);434 // partial return435 } else if (partial) {436 return str;437 // render complete, and 438 // callback given439 } else if (fn) {440 fn(null, str);441 // respond442 } else {443 this.send(str);444 }445}446447/**448 * Hint at view path resolution, outputting the449 * paths that Express has tried.450 *451 * @api private452 */453454function hintAtViewPaths(view, options) {455 console.error();456 console.error('failed to locate view "' + view.view + '", tried:');457 options.attempts.forEach(function(path){458 console.error(' - %s', path);459 });460 console.error();461}