Skip to content
Myr

view.js

This file

Path

lib/view.js

434 lines · 9.9 KiB · JavaScript

Last changed by

Added support for routes to handle errors. Closes #809Tj Holowaychukbefore adoptionf977272

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  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      }183    }184    return res.render(view, options, null, parent, true);185  }186187  // Collection support188  if (collection) {189    var len = collection.length190      , buf = ''191      , keys192      , key193      , val;194195    options.collectionLength = len;196197    if ('number' == typeof len || Array.isArray(collection)) {198      for (var i = 0; i < len; ++i) {199        val = collection[i];200        options.firstInCollection = i == 0;201        options.indexInCollection = i;202        options.lastInCollection = i == len - 1;203        object = val;204        buf += render();205      }      206    } else {207      keys = Object.keys(collection);208      len = keys.length;209      options.collectionLength = len;210      options.collectionKeys = keys;211      for (var i = 0; i < len; ++i) {212        key = keys[i];213        val = collection[key];214        options.keyInCollection = key;215        options.firstInCollection = i == 0;216        options.indexInCollection = i;217        options.lastInCollection = i == len - 1;218        object = val;219        buf += render();220      }221    }222223    return buf;224  } else {225    return render();226  }227};228229/**230 * Render `view` partial with the given `options`. Optionally a 231 * callback `fn(err, str)` may be passed instead of writing to232 * the socket.233 *234 * Options:235 *236 *   - `object` Single object with name derived from the view (unless `as` is present) 237 *238 *   - `as` Variable name for each `collection` value, defaults to the view name.239 *     * as: 'something' will add the `something` local variable240 *     * as: this will use the collection value as the template context241 *     * as: global will merge the collection value's properties with `locals`242 *243 *   - `collection` Array of objects, the name is derived from the view name itself. 244 *     For example _video.html_ will have a object _video_ available to it.245 *246 * @param  {String} view247 * @param  {Object|Array|Function} options, collection, callback, or object248 * @param  {Function} fn249 * @return {String}250 * @api public251 */252253res.partial = function(view, options, fn){254  var app = this.app255    , options = options || {}256    , viewEngine = app.set('view engine')257    , parent = {};258259  // accept callback as second argument260  if ('function' == typeof options) {261    fn = options;262    options = {};263  }264265  // root "views" option266  parent.dirname = app.set('views') || process.cwd() + '/views';267268  // utilize "view engine" option269  if (viewEngine) parent.engine = viewEngine;270271  // render the partial272  try {273    var str = renderPartial(this, view, options, null, parent);274  } catch (err) {275    if (fn) {276      fn(err);277    } else {278      this.req.next(err);279    }280    return;281  }282283  // callback or transfer284  if (fn) {285    fn(null, str);286  } else {287    this.send(str);288  }289};290291/**292 * Render `view` with the given `options` and optional callback `fn`.293 * When a callback function is given a response will _not_ be made294 * automatically, however otherwise a response of _200_ and _text/html_ is given.295 *296 * Options:297 *  298 *  - `scope`     Template evaluation context (the value of `this`)299 *  - `debug`     Output debugging information300 *  - `status`    Response status code301 *302 * @param  {String} view303 * @param  {Object|Function} options or callback function304 * @param  {Function} fn305 * @api public306 */307308res.render = function(view, opts, fn, parent, sub){309  // support callback function as second arg310  if ('function' == typeof opts) {311    fn = opts, opts = null;312  }313314  try {315    return this._render(view, opts, fn, parent, sub);316  } catch (err) {317    // callback given318    if (fn) {319      fn(err);320    // unwind to root call to prevent multiple callbacks321    } else if (sub) {322      throw err;323    // root template, next(err)324    } else {325      this.req.next(err);326    }327  }328};329330// private render()331332res._render = function(view, opts, fn, parent, sub){333  var options = {}334    , self = this335    , app = this.app336    , root = app.set('views') || process.cwd() + '/views';337338  // cache id339  var cid = app.enabled('view cache')340    ? view + (parent ? ':' + parent.path : '')341    : false;342343  // merge app.locals344  union(options, app.locals);345346  // merge res.locals347  merge(options, this.locals);348349  // merge render() options350  if (opts) merge(options, opts);351352  // merge render() .locals353  if (opts && opts.locals) merge(options, opts.locals);354355  // status support356  if (options.status) this.statusCode = options.status;357358  // capture attempts359  options.attempts = [];360361  var partial = options.isPartial362    , layout = options.layout;363364  // Layout support365  if (true === layout || undefined === layout) {366    layout = 'layout';367  }368369  // Default execution scope to a plain object370  options.scope = options.scope || {};371372  // Populate view373  options.parentView = parent;374375  // "views" setting376  options.root = root;377378  // "view engine" setting379  options.defaultEngine = app.set('view engine');380381  // charset option382  if (options.charset) this.charset = options.charset;383384  // Always expose partial() as a local385  options.partial = function(path, opts){386    return renderPartial(self, path, opts, options, view);387  };388389  // View lookup390  options.hint = app.enabled('hints');391  view = exports.compile(view, app.cache, cid, options);392393  // layout helper394  options.layout = function(path){395    layout = path;396  };397398  // render399  var str = view.fn.call(options.scope, options);400401  // layout expected402  if (layout) {403    options.isLayout = true;404    options.layout = false;405    options.body = str;406    this.render(layout, options, fn, view, true);407  // partial return408  } else if (partial) {409    return str;410  // render complete, and 411  // callback given412  } else if (fn) {413    fn(null, str);414  // respond415  } else {416    this.send(str);417  }418}419420/**421 * Hint at view path resolution, outputting the422 * paths that Express has tried.423 *424 * @api private425 */426427function hintAtViewPaths(view, options) {428  console.error();429  console.error('failed to locate view "' + view.view + '", tried:');430  options.attempts.forEach(function(path){431    console.error('  - %s', path);432  });433  console.error();434}