view.js
This file
Path
lib/view.js
278 lines · 6.7 KiB · JavaScript
Last changed by
moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
History of this fileTake it
moved files from lib/express/* to lib/Tj Holowaychukbefore adoption3d597a5
lines 1–278why, one step back12/*!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.merge21 , http = require('http')22 , mime = utils.mime;2324/**25 * Memory cache.26 *27 * @type Object28 */2930var cache = {};3132/**33 * Expose constructors.34 */3536exports = module.exports = View;37exports.Partial = Partial;3839/**40 * Export template engine registrar.41 */4243exports.register = View.register;4445/**46 * Render `view` partial with the given `options`.47 *48 * Options:49 * - `object` Single object with name derived from the view (unless `as` is present) 50 *51 * - `as` Variable name for each `collection` value, defaults to the view name.52 * * as: 'something' will add the `something` local variable53 * * as: this will use the collection value as the template context54 * * as: global will merge the collection value's properties with `locals`55 *56 * - `collection` Array of objects, the name is derived from the view name itself. 57 * For example _video.html_ will have a object _video_ available to it.58 *59 * @param {String} view60 * @param {Object|Array} options, collection, or object61 * @return {String}62 * @api public63 */6465http.ServerResponse.prototype.partial = function(view, options, locals, parent){66 var self = this;6768 // Inherit parent view extension when not present69 if (parent && !~view.indexOf('.')) {70 view += parent.extension;71 }7273 // Allow collection to be passed as second param74 if (options) {75 if ('length' in options) {76 options = { collection: options };77 } else if (!options.collection && !options.locals && !options.object) {78 options = { object: options };79 }80 } else {81 options = {};82 }8384 // Inherit locals from parent85 merge(options, locals);86 87 // Merge locals88 if (options.locals) {89 merge(options, options.locals);90 }9192 // Partials dont need layouts93 options.renderPartial = true;94 options.layout = false;9596 // Deduce name from view path97 var name = options.as || Partial.resolveObjectName(view);9899 // Render partial100 function render(){101 if (options.object) {102 if ('string' == typeof name) {103 options[name] = options.object;104 } else if (name === global) {105 merge(options, options.object);106 } else {107 options.scope = options.object;108 }109 }110 return self.render(view, options, null, parent);111 }112113 // Collection support114 var collection = options.collection;115 if (collection) {116 var len = collection.length117 , buf = '';118 delete options.collection;119 options.collectionLength = len;120 for (var i = 0; i < len; ++i) {121 var val = collection[i];122 options.firstInCollection = i === 0;123 options.indexInCollection = i;124 options.lastInCollection = i === len - 1;125 options.object = val;126 buf += render();127 }128 return buf;129 } else {130 return render();131 }132};133134/**135 * Render `view` with the given `options` and optional callback `fn`.136 * When a callback function is given a response will _not_ be made137 * automatically, however otherwise a response of _200_ and _text/html_ is given.138 *139 * Options:140 * 141 * Most engines accept one or more of the following options,142 * both _haml_ and _jade_ accept all:143 *144 * - `scope` Template evaluation context (the value of `this`)145 * - `debug` Output debugging information146 * - `status` Response status code, defaults to 200147 * - `headers` Response headers object148 *149 * @param {String} view150 * @param {Object|Function} options or callback function151 * @param {Function} fn152 * @api public153 */154155http.ServerResponse.prototype.render = function(view, options, fn, parent){156 // Support callback function as second arg157 if (typeof options === 'function') {158 fn = options, options = {};159 }160 161 var self = this162 , app = this.app163 , options = options || {}164 , helpers = app.viewHelpers165 , dynamicHelpers = app.dynamicViewHelpers166 , viewOptions = app.settings['view options']167 , cacheTemplates = app.settings['cache views'];168169 // Merge "view options"170 if (viewOptions) options = merge(clone(viewOptions), options);171172 // Defaults173 var self = this174 , root = app.settings.views || process.cwd() + '/views'175 , partial = options.renderPartial176 , layout = options.layout;177178 // Layout support179 if (true === layout || undefined === layout) {180 layout = 'layout';181 }182183 // Default execution scope to the response184 options.scope = options.scope || this.req;185186 // Populate view187 options.parentView = parent;188189 // "views" setting190 options.root = root;191192 // "view engine" setting193 options.defaultEngine = app.settings['view engine'];194195 // Populate view196 // TODO: cache197 var orig = view = partial198 ? new Partial(view, options)199 : new View(view, options);200201 // Ensure view exists, otherwise try _ prefix202 if (!view.exists) {203 view = partial204 ? new Partial(view.prefixPath, options)205 : new View(view.prefixPath, options);206 }207 208 // Ensure view _ prefix exists, otherwise try index209 if (!view.exists) {210 view = partial211 ? new Partial(orig.indexPath, options)212 : new View(orig.indexPath, options);213 }214 215 // Merge res.locals216 if (this.locals) {217 options = merge(this.locals, options);218 }219 220 // Dynamic helper support221 if (false !== options.dynamicHelpers) {222 // cache223 if (!this.__dynamicHelpers) {224 this.__dynamicHelpers = {};225 for (var key in dynamicHelpers) {226 this.__dynamicHelpers[key] = dynamicHelpers[key].call(227 this.app228 , this.req229 , this);230 }231 }232233 // apply234 merge(options, this.__dynamicHelpers);235 }236237 // Merge view helpers238 options = merge(clone(helpers), options);239240 // Always expose partial() as a local241 options.partial = function(path, opts){242 return self.partial(path, opts, options, view);243 };244245 function error(err) {246 if (fn) {247 fn(err);248 } else {249 self.req.next(err);250 }251 }252253 // Attempt render254 try {255 var engine = view.templateEngine256 , template = cacheTemplates257 ? cache[view.path] || (cache[view.path] = engine.compile(view.contents, options))258 : engine.compile(view.contents, options)259 , str = template.call(options.scope, options);260 } catch (err) {261 return error(err);262 }263264 // Layout support265 if (layout) {266 options.isLayout = true;267 options.layout = false;268 options.body = str;269 options.relative = false;270 self.render(layout, options, fn, view);271 } else if (partial) {272 return str;273 } else if (fn) {274 fn(null, str);275 } else {276 this.send(str, options.headers, options.status);277 }278};