view.js 10.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

/*!
 * Express - view
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var path = require('path')
  , extname = path.extname
  , dirname = path.dirname
  , basename = path.basename
  , utils = require('connect').utils
  , View = require('./view/view')
  , partial = require('./view/partial')
  , union = require('./utils').union
  , merge = utils.merge
  , http = require('http')
  , res = http.ServerResponse.prototype;

/**
 * Expose constructors.
 */

exports = module.exports = View;

/**
 * Export template engine registrar.
 */

exports.register = View.register;

/**
 * Lookup and compile `view` with cache support by supplying
 * both the `cache` object and `cid` string,
 * followed by `options` passed to `exports.lookup()`.
 *
 * @param {String} view
 * @param {Object} cache
 * @param {Object} cid
 * @param {Object} options
 * @return {View}
 * @api private
 */

exports.compile = function(view, cache, cid, options){
  if (cache && cid && cache[cid]){
    options.filename = cache[cid].path;
    return cache[cid];
  }

  // lookup
  view = exports.lookup(view, options);

  // hints
  if (!view.exists) {
    if (options.hint) hintAtViewPaths(view.original, options);
    var err = new Error('failed to locate view "' + view.original.view + '"');
    err.view = view.original;
    throw err;
  }

  // compile
  options.filename = view.path;
  view.fn = view.templateEngine.compile(view.contents, options);
  cache[cid] = view;

  return view;
};

/**
 * Lookup `view`, returning an instanceof `View`.
 *
 * Options:
 *
 *   - `root` root directory path
 *   - `defaultEngine` default template engine
 *   - `parentView` parent `View` object
 *   - `cache` cache object
 *   - `cacheid` optional cache id
 *
 * Lookup:
 *
 *   - partial `_<name>`
 *   - any `<name>/index`
 *   - non-layout `../<name>/index`
 *   - any `<root>/<name>`
 *   - partial `<root>/_<name>`
 *
 * @param {String} view
 * @param {Object} options
 * @return {View}
 * @api private
 */

exports.lookup = function(view, options){
  var orig = view = new View(view, options)
    , partial = options.isPartial
    , layout = options.isLayout;

  // Try _ prefix ex: ./views/_<name>.jade
  // taking precedence over the direct path
  if (partial) {
    view = new View(orig.prefixPath, options);
    if (!view.exists) view = orig;
  }

  // Try index ex: ./views/user/index.jade
  if (!layout && !view.exists) view = new View(orig.indexPath, options);

  // Try ../<name>/index ex: ../user/index.jade
  // when calling partial('user') within the same dir
  if (!layout && !view.exists) view = new View(orig.upIndexPath, options);

  // Try root ex: <root>/user.jade
  if (!view.exists) view = new View(orig.rootPath, options);

  // Try root _ prefix ex: <root>/_user.jade
  if (!view.exists && partial) view = new View(view.prefixPath, options);

  view.original = orig;
  return view;
};

/**
 * Partial render helper.
 *
 * @api private
 */

function renderPartial(res, view, options, parentLocals, parent){
  var collection, object, locals;

  if (options) {
    // collection
    if (options.collection) {
      collection = options.collection;
      delete options.collection;
    } else if ('length' in options) {
      collection = options;
      options = {};
    }

    // locals
    if (options.locals) {
      locals = options.locals;
      delete options.locals;
    }

    // object
    if ('Object' != options.constructor.name) {
      object = options;
      options = {};
    } else if (undefined != options.object) {
      object = options.object;
      delete options.object;
    }
  } else {
    options = {};
  }

  // Inherit locals from parent
  union(options, parentLocals);

  // Merge locals
  if (locals) merge(options, locals);

  // Partials dont need layouts
  options.isPartial = true;
  options.layout = false;

  // Deduce name from view path
  var name = options.as || partial.resolveObjectName(view);

  // Render partial
  function render(){
    if (object) {
      if ('string' == typeof name) {
        options[name] = object;
      } else if (name === global) {
        merge(options, object);
      }
    }
    return res.render(view, options, null, parent, true);
  }

  // Collection support
  if (collection) {
    var len = collection.length
      , buf = ''
      , keys
      , key
      , val;

    options.collectionLength = len;

    if ('number' == typeof len || Array.isArray(collection)) {
      for (var i = 0; i < len; ++i) {
        val = collection[i];
        options.firstInCollection = i == 0;
        options.indexInCollection = i;
        options.lastInCollection = i == len - 1;
        object = val;
        buf += render();
      }
    } else {
      keys = Object.keys(collection);
      len = keys.length;
      options.collectionLength = len;
      options.collectionKeys = keys;
      for (var i = 0; i < len; ++i) {
        key = keys[i];
        val = collection[key];
        options.keyInCollection = key;
        options.firstInCollection = i == 0;
        options.indexInCollection = i;
        options.lastInCollection = i == len - 1;
        object = val;
        buf += render();
      }
    }

    return buf;
  } else {
    return render();
  }
};

/**
 * Render `view` partial with the given `options`. Optionally a
 * callback `fn(err, str)` may be passed instead of writing to
 * the socket.
 *
 * Options:
 *
 *   - `object` Single object with name derived from the view (unless `as` is present)
 *
 *   - `as` Variable name for each `collection` value, defaults to the view name.
 *     * as: 'something' will add the `something` local variable
 *     * as: this will use the collection value as the template context
 *     * as: global will merge the collection value's properties with `locals`
 *
 *   - `collection` Array of objects, the name is derived from the view name itself.
 *     For example _video.html_ will have a object _video_ available to it.
 *
 * @param  {String} view
 * @param  {Object|Array|Function} options, collection, callback, or object
 * @param  {Function} fn
 * @return {String}
 * @api public
 */

res.partial = function(view, options, fn){
  var app = this.app
    , options = options || {}
    , viewEngine = app.set('view engine')
    , parent = {};

  // accept callback as second argument
  if ('function' == typeof options) {
    fn = options;
    options = {};
  }

  // root "views" option
  parent.dirname = app.set('views') || process.cwd() + '/views';

  // utilize "view engine" option
  if (viewEngine) parent.engine = viewEngine;

  // render the partial
  try {
    var str = renderPartial(this, view, options, null, parent);
  } catch (err) {
    if (fn) {
      fn(err);
    } else {
      this.req.next(err);
    }
    return;
  }

  // callback or transfer
  if (fn) {
    fn(null, str);
  } else {
    this.send(str);
  }
};

/**
 * Render `view` with the given `options` and optional callback `fn`.
 * When a callback function is given a response will _not_ be made
 * automatically, however otherwise a response of _200_ and _text/html_ is given.
 *
 * Options:
 *
 *  - `scope`     Template evaluation context (the value of `this`)
 *  - `debug`     Output debugging information
 *  - `status`    Response status code
 *
 * @param  {String} view
 * @param  {Object|Function} options or callback function
 * @param  {Function} fn
 * @api public
 */

res.render = function(view, opts, fn, parent, sub){
  // support callback function as second arg
  if ('function' == typeof opts) {
    fn = opts, opts = null;
  }

  try {
    return this._render(view, opts, fn, parent, sub);
  } catch (err) {
    // callback given
    if (fn) {
      fn(err);
    // unwind to root call to prevent multiple callbacks
    } else if (sub) {
      throw err;
    // root template, next(err)
    } else {
      this.req.next(err);
    }
  }
};

// private render()

res._render = function(view, opts, fn, parent, sub){
  var options = {}
    , self = this
    , app = this.app
    , helpers = app._locals
    , dynamicHelpers = app.dynamicViewHelpers
    , viewOptions = app.set('view options')
    , root = app.set('views') || process.cwd() + '/views';

  // cache id
  var cid = app.enabled('view cache')
    ? view + (parent ? ':' + parent.path : '')
    : false;

  // merge "view options"
  if (viewOptions) merge(options, viewOptions);

  // merge res._locals
  if (this._locals) merge(options, this._locals);

  // merge render() options
  if (opts) merge(options, opts);

  // merge render() .locals
  if (opts && opts.locals) merge(options, opts.locals);

  // status support
  if (options.status) this.statusCode = options.status;

  // capture attempts
  options.attempts = [];

  var partial = options.isPartial
    , layout = options.layout;

  // Layout support
  if (true === layout || undefined === layout) {
    layout = 'layout';
  }

  // Default execution scope to a plain object
  options.scope = options.scope || {};

  // Populate view
  options.parentView = parent;

  // "views" setting
  options.root = root;

  // "view engine" setting
  options.defaultEngine = app.set('view engine');

  // charset option
  if (options.charset) this.charset = options.charset;

  // Dynamic helper support
  if (false !== options.dynamicHelpers) {
    // cache
    if (!this.__dynamicHelpers) {
      this.__dynamicHelpers = {};
      for (var key in dynamicHelpers) {
        this.__dynamicHelpers[key] = dynamicHelpers[key].call(
            this.app
          , this.req
          , this);
      }
    }

    // apply
    merge(options, this.__dynamicHelpers);
  }

  // Merge view helpers
  union(options, helpers);

  // Always expose partial() as a local
  options.partial = function(path, opts){
    return renderPartial(self, path, opts, options, view);
  };

  // View lookup
  options.hint = app.enabled('hints');
  view = exports.compile(view, app.cache, cid, options);

  // layout helper
  options.layout = function(path){
    layout = path;
  };

  // render
  var str = view.fn.call(options.scope, options);

  // layout expected
  if (layout) {
    options.isLayout = true;
    options.layout = false;
    options.body = str;
    this.render(layout, options, fn, view, true);
  // partial return
  } else if (partial) {
    return str;
  // render complete, and
  // callback given
  } else if (fn) {
    fn(null, str);
  // respond
  } else {
    this.send(str);
  }
}

/**
 * Hint at view path resolution, outputting the
 * paths that Express has tried.
 *
 * @api private
 */

function hintAtViewPaths(view, options) {
  console.error();
  console.error('failed to locate view "' + view.view + '", tried:');
  options.attempts.forEach(function(path){
    console.error('  - %s', path);
  });
  console.error();
}