Skip to content
Myr

view.js

This file

Path

lib/view.js

277 lines · 6.7 KiB · JavaScript

Last changed by

replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85

History of this file

Take it

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 1–20why, one step back
1
2/*!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 , clone = require('./utils').clone18 , View = require('./view/view')19 , Partial = require('./view/partial')20 , merge = utils.merge

replaced connect.utils.mime() with mime moduleTj Holowaychukbefore adoptiond37ad85

line 21why, one step back
21 , http = require('http');

moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5

lines 22–277why, one step back
22
23/**24 * Memory cache.25 *26 * @type Object27 */2829var cache = {};3031/**32 * Expose constructors.33 */3435exports = module.exports = View;36exports.Partial = Partial;3738/**39 * Export template engine registrar.40 */4142exports.register = View.register;4344/**45 * Render `view` partial with the given `options`.46 *47 * Options:48 * - `object` Single object with name derived from the view (unless `as` is present) 49 *50 * - `as` Variable name for each `collection` value, defaults to the view name.51 * * as: 'something' will add the `something` local variable52 * * as: this will use the collection value as the template context53 * * as: global will merge the collection value's properties with `locals`54 *55 * - `collection` Array of objects, the name is derived from the view name itself. 56 * For example _video.html_ will have a object _video_ available to it.57 *58 * @param {String} view59 * @param {Object|Array} options, collection, or object60 * @return {String}61 * @api public62 */6364http.ServerResponse.prototype.partial = function(view, options, locals, parent){65 var self = this;6667 // Inherit parent view extension when not present68 if (parent && !~view.indexOf('.')) {69 view += parent.extension;70 }7172 // Allow collection to be passed as second param73 if (options) {74 if ('length' in options) {75 options = { collection: options };76 } else if (!options.collection && !options.locals && !options.object) {77 options = { object: options };78 }79 } else {80 options = {};81 }8283 // Inherit locals from parent84 merge(options, locals);85 86 // Merge locals87 if (options.locals) {88 merge(options, options.locals);89 }9091 // Partials dont need layouts92 options.renderPartial = true;93 options.layout = false;9495 // Deduce name from view path96 var name = options.as || Partial.resolveObjectName(view);9798 // Render partial99 function render(){100 if (options.object) {101 if ('string' == typeof name) {102 options[name] = options.object;103 } else if (name === global) {104 merge(options, options.object);105 } else {106 options.scope = options.object;107 }108 }109 return self.render(view, options, null, parent);110 }111112 // Collection support113 var collection = options.collection;114 if (collection) {115 var len = collection.length116 , buf = '';117 delete options.collection;118 options.collectionLength = len;119 for (var i = 0; i < len; ++i) {120 var val = collection[i];121 options.firstInCollection = i === 0;122 options.indexInCollection = i;123 options.lastInCollection = i === len - 1;124 options.object = val;125 buf += render();126 }127 return buf;128 } else {129 return render();130 }131};132133/**134 * Render `view` with the given `options` and optional callback `fn`.135 * When a callback function is given a response will _not_ be made136 * automatically, however otherwise a response of _200_ and _text/html_ is given.137 *138 * Options:139 * 140 * Most engines accept one or more of the following options,141 * both _haml_ and _jade_ accept all:142 *143 * - `scope` Template evaluation context (the value of `this`)144 * - `debug` Output debugging information145 * - `status` Response status code, defaults to 200146 * - `headers` Response headers object147 *148 * @param {String} view149 * @param {Object|Function} options or callback function150 * @param {Function} fn151 * @api public152 */153154http.ServerResponse.prototype.render = function(view, options, fn, parent){155 // Support callback function as second arg156 if (typeof options === 'function') {157 fn = options, options = {};158 }159 160 var self = this161 , app = this.app162 , options = options || {}163 , helpers = app.viewHelpers164 , dynamicHelpers = app.dynamicViewHelpers165 , viewOptions = app.settings['view options']166 , cacheTemplates = app.settings['cache views'];167168 // Merge "view options"169 if (viewOptions) options = merge(clone(viewOptions), options);170171 // Defaults172 var self = this173 , root = app.settings.views || process.cwd() + '/views'174 , partial = options.renderPartial175 , layout = options.layout;176177 // Layout support178 if (true === layout || undefined === layout) {179 layout = 'layout';180 }181182 // Default execution scope to the response183 options.scope = options.scope || this.req;184185 // Populate view186 options.parentView = parent;187188 // "views" setting189 options.root = root;190191 // "view engine" setting192 options.defaultEngine = app.settings['view engine'];193194 // Populate view195 // TODO: cache196 var orig = view = partial197 ? new Partial(view, options)198 : new View(view, options);199200 // Ensure view exists, otherwise try _ prefix201 if (!view.exists) {202 view = partial203 ? new Partial(view.prefixPath, options)204 : new View(view.prefixPath, options);205 }206 207 // Ensure view _ prefix exists, otherwise try index208 if (!view.exists) {209 view = partial210 ? new Partial(orig.indexPath, options)211 : new View(orig.indexPath, options);212 }213 214 // Merge res.locals215 if (this.locals) {216 options = merge(this.locals, options);217 }218 219 // Dynamic helper support220 if (false !== options.dynamicHelpers) {221 // cache222 if (!this.__dynamicHelpers) {223 this.__dynamicHelpers = {};224 for (var key in dynamicHelpers) {225 this.__dynamicHelpers[key] = dynamicHelpers[key].call(226 this.app227 , this.req228 , this);229 }230 }231232 // apply233 merge(options, this.__dynamicHelpers);234 }235236 // Merge view helpers237 options = merge(clone(helpers), options);238239 // Always expose partial() as a local240 options.partial = function(path, opts){241 return self.partial(path, opts, options, view);242 };243244 function error(err) {245 if (fn) {246 fn(err);247 } else {248 self.req.next(err);249 }250 }251252 // Attempt render253 try {254 var engine = view.templateEngine255 , template = cacheTemplates256 ? cache[view.path] || (cache[view.path] = engine.compile(view.contents, options))257 : engine.compile(view.contents, options)258 , str = template.call(options.scope, options);259 } catch (err) {260 return error(err);261 }262263 // Layout support264 if (layout) {265 options.isLayout = true;266 options.layout = false;267 options.body = str;268 options.relative = false;269 self.render(layout, options, fn, view);270 } else if (partial) {271 return str;272 } else if (fn) {273 fn(null, str);274 } else {275 this.send(str, options.headers, options.status);276 }277};