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

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  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.length188      , buf = ''189      , keys190      , key191      , val;192193    options.collectionLength = len;194195    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];212        options.keyInCollection = key;213        options.firstInCollection = i == 0;214        options.indexInCollection = i;215        options.lastInCollection = i == len - 1;216        object = val;217        buf += render();218      }219    }220221    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 || {}254    , viewEngine = app.set('view engine')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" option267  if (viewEngine) parent.engine = viewEngine;268269  // render the partial270  try {271    var str = renderPartial(this, view, options, null, parent);272  } catch (err) {273    if (fn) {274      fn(err);275    } else {276      this.req.next(err);277    }278    return;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);318    // unwind to root call to prevent319    // several next(err) calls320    } 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.app335    , helpers = app._locals336    , dynamicHelpers = app.dynamicViewHelpers337    , viewOptions = app.set('view options')338    , root = app.set('views') || process.cwd() + '/views';339340  // cache id341  var cid = app.enabled('view cache')342    ? view + (parent ? ':' + parent.path : '')343    : false;344345  // 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;359360  // capture attempts361  options.attempts = [];362363  var partial = options.renderPartial364    , 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  };410411  // View lookup412  options.hint = app.enabled('hints');413  view = exports.compile(view, app.cache, cid, options);414  options.filename = view.path;415416  // layout helper417  options.layout = function(path){418    layout = path;419  };420421  // render422  var str = view.fn.call(options.scope, options);423424  // 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:');453  options.attempts.forEach(function(path){454    console.error('  - %s', path);455  });456  console.error();457}