Skip to content
Myr

view.js

This file

Path

lib/view.js

459 lines · 10.5 KiB · JavaScript

Last changed by

`app.dynamicHelpers` -> `app.dynamicLocals`Tj Holowaychukbefore adoption336aaae

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)97    , partial = options.isPartial98    , layout = options.isLayout;99100  // Try _ prefix ex: ./views/_<name>.jade101  // taking precedence over the direct path102  if (partial) {103    view = new View(orig.prefixPath, options);104    if (!view.exists) view = orig;105  }106107  // Try index ex: ./views/user/index.jade108  if (!layout && !view.exists) view = new View(orig.indexPath, options);109110  // Try ../<name>/index ex: ../user/index.jade111  // when calling partial('user') within the same dir112  if (!layout && !view.exists) view = new View(orig.upIndexPath, options);113114  // Try root ex: <root>/user.jade115  if (!view.exists) view = new View(orig.rootPath, options);116117  // Try root _ prefix ex: <root>/_user.jade118  if (!view.exists && partial) view = new View(view.prefixPath, options);119120  view.original = orig;121  return view;122};123124/**125 * Partial render helper.126 *127 * @api private128 */129130function renderPartial(res, view, options, parentLocals, parent){131  var collection, object, locals;132133  if (options) {134    // collection135    if (options.collection) {136      collection = options.collection;137      delete options.collection;138    } else if ('length' in options) {139      collection = options;140      options = {};141    }142143    // locals144    if (options.locals) {145      locals = options.locals;146      delete options.locals;147    }148149    // object150    if ('Object' != options.constructor.name) {151      object = options;152      options = {};153    } else if (undefined != options.object) {154      object = options.object;155      delete options.object;156    }157  } else {158    options = {};159  }160161  // Inherit locals from parent162  union(options, parentLocals);163  164  // Merge locals165  if (locals) merge(options, locals);166167  // Partials dont need layouts168  options.isPartial = true;169  options.layout = false;170171  // Deduce name from view path172  var name = options.as || partial.resolveObjectName(view);173174  // Render partial175  function render(){176    if (object) {177      if ('string' == typeof name) {178        options[name] = object;179      } else if (name === global) {180        merge(options, object);181      } else {182        options.scope = object;183      }184    }185    return res.render(view, options, null, parent, true);186  }187188  // Collection support189  if (collection) {190    var len = collection.length191      , buf = ''192      , keys193      , key194      , val;195196    options.collectionLength = len;197198    if ('number' == typeof len || Array.isArray(collection)) {199      for (var i = 0; i < len; ++i) {200        val = collection[i];201        options.firstInCollection = i == 0;202        options.indexInCollection = i;203        options.lastInCollection = i == len - 1;204        object = val;205        buf += render();206      }      207    } else {208      keys = Object.keys(collection);209      len = keys.length;210      options.collectionLength = len;211      options.collectionKeys = keys;212      for (var i = 0; i < len; ++i) {213        key = keys[i];214        val = collection[key];215        options.keyInCollection = key;216        options.firstInCollection = i == 0;217        options.indexInCollection = i;218        options.lastInCollection = i == len - 1;219        object = val;220        buf += render();221      }222    }223224    return buf;225  } else {226    return render();227  }228};229230/**231 * Render `view` partial with the given `options`. Optionally a 232 * callback `fn(err, str)` may be passed instead of writing to233 * the socket.234 *235 * Options:236 *237 *   - `object` Single object with name derived from the view (unless `as` is present) 238 *239 *   - `as` Variable name for each `collection` value, defaults to the view name.240 *     * as: 'something' will add the `something` local variable241 *     * as: this will use the collection value as the template context242 *     * as: global will merge the collection value's properties with `locals`243 *244 *   - `collection` Array of objects, the name is derived from the view name itself. 245 *     For example _video.html_ will have a object _video_ available to it.246 *247 * @param  {String} view248 * @param  {Object|Array|Function} options, collection, callback, or object249 * @param  {Function} fn250 * @return {String}251 * @api public252 */253254res.partial = function(view, options, fn){255  var app = this.app256    , options = options || {}257    , viewEngine = app.set('view engine')258    , parent = {};259260  // accept callback as second argument261  if ('function' == typeof options) {262    fn = options;263    options = {};264  }265266  // root "views" option267  parent.dirname = app.set('views') || process.cwd() + '/views';268269  // utilize "view engine" option270  if (viewEngine) parent.engine = viewEngine;271272  // render the partial273  try {274    var str = renderPartial(this, view, options, null, parent);275  } catch (err) {276    if (fn) {277      fn(err);278    } else {279      this.req.next(err);280    }281    return;282  }283284  // callback or transfer285  if (fn) {286    fn(null, str);287  } else {288    this.send(str);289  }290};291292/**293 * Render `view` with the given `options` and optional callback `fn`.294 * When a callback function is given a response will _not_ be made295 * automatically, however otherwise a response of _200_ and _text/html_ is given.296 *297 * Options:298 *  299 *  - `scope`     Template evaluation context (the value of `this`)300 *  - `debug`     Output debugging information301 *  - `status`    Response status code302 *303 * @param  {String} view304 * @param  {Object|Function} options or callback function305 * @param  {Function} fn306 * @api public307 */308309res.render = function(view, opts, fn, parent, sub){310  // support callback function as second arg311  if ('function' == typeof opts) {312    fn = opts, opts = null;313  }314315  try {316    return this._render(view, opts, fn, parent, sub);317  } catch (err) {318    // callback given319    if (fn) {320      fn(err);321    // unwind to root call to prevent multiple callbacks322    } else if (sub) {323      throw err;324    // root template, next(err)325    } else {326      this.req.next(err);327    }328  }329};330331// private render()332333res._render = function(view, opts, fn, parent, sub){334  var options = {}335    , self = this336    , app = this.app337    , helpers = app._locals338    , dynamic = app._dynamicLocals339    , viewOptions = app.set('view options')340    , 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 "view options"348  if (viewOptions) merge(options, viewOptions);349350  // merge res._locals351  if (this._locals) merge(options, this._locals);352353  // merge render() options354  if (opts) merge(options, opts);355356  // merge render() .locals357  if (opts && opts.locals) merge(options, opts.locals);358359  // status support360  if (options.status) this.statusCode = options.status;361362  // capture attempts363  options.attempts = [];364365  var partial = options.isPartial366    , layout = options.layout;367368  // Layout support369  if (true === layout || undefined === layout) {370    layout = 'layout';371  }372373  // Default execution scope to a plain object374  options.scope = options.scope || {};375376  // Populate view377  options.parentView = parent;378379  // "views" setting380  options.root = root;381382  // "view engine" setting383  options.defaultEngine = app.set('view engine');384385  // charset option386  if (options.charset) this.charset = options.charset;387388  // Dynamic helper support389  if (false !== options.dynamic) {390    // cache391    if (!this.__dynamic) {392      this.__dynamic = {};393      for (var key in dynamic) {394        this.__dynamic[key] = dynamic[key].call(395            this.app396          , this.req397          , this);398      }399    }400401    // apply402    merge(options, this.__dynamic);403  }404405  // Merge view helpers406  union(options, helpers);407408  // Always expose partial() as a local409  options.partial = function(path, opts){410    return renderPartial(self, path, opts, options, view);411  };412413  // View lookup414  options.hint = app.enabled('hints');415  view = exports.compile(view, app.cache, cid, options);416  options.filename = view.path;417418  // layout helper419  options.layout = function(path){420    layout = path;421  };422423  // render424  var str = view.fn.call(options.scope, options);425426  // layout expected427  if (layout) {428    options.isLayout = true;429    options.layout = false;430    options.body = str;431    this.render(layout, options, fn, view, true);432  // partial return433  } else if (partial) {434    return str;435  // render complete, and 436  // callback given437  } else if (fn) {438    fn(null, str);439  // respond440  } else {441    this.send(str);442  }443}444445/**446 * Hint at view path resolution, outputting the447 * paths that Express has tried.448 *449 * @api private450 */451452function hintAtViewPaths(view, options) {453  console.error();454  console.error('failed to locate view "' + view.view + '", tried:');455  options.attempts.forEach(function(path){456    console.error('  - %s', path);457  });458  console.error();459}