Skip to content
Myr

re-working view system

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent ce03cf4 · Browse files · 8 files+128 added−646 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+128 added−646 removed

  • other:+128 added−646 removed

8 files+128 added−646 removed

deleted:lib/view/partial.js-40 removed
deleted:lib/view/view.js-210 removed
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 , utils = require('../utils')14 , extname = path.extname15 , dirname = path.dirname16 , basename = path.basename17 , fs = require('fs')18 , stat = fs.statSync;1920/**21 * Expose `View`.22 */2324exports = module.exports = View;2526/**27 * Require cache.28 */2930var cache = {};3132/**33 * Initialize a new `View` with the given `view` path and `options`.34 *35 * @param {String} view36 * @param {Object} options37 * @api private38 */3940function View(view, options) {41 options = options || {};42 this.view = view;43 this.root = options.root;44 this.relative = false !== options.relative;45 this.defaultEngine = options.defaultEngine;46 this.parent = options.parentView;47 this.basename = basename(view);48 this.engine = this.resolveEngine();49 this.extension = '.' + this.engine;50 this.name = this.basename.replace(this.extension, '');51 this.path = this.resolvePath();52 this.dirname = dirname(this.path);53 if (options.attempts) {54 if (!~options.attempts.indexOf(this.path))55 options.attempts.push(this.path);56 }57};5859/**60 * Check if the view path exists.61 *62 * @return {Boolean}63 * @api public64 */6566View.prototype.__defineGetter__('exists', function(){67 try {68 stat(this.path);69 return true;70 } catch (err) {71 return false;72 }73});7475/**76 * Resolve view engine.77 *78 * @return {String}79 * @api private80 */8182View.prototype.resolveEngine = function(){83 // Explicit84 if (~this.basename.indexOf('.')) return extname(this.basename).substr(1);85 // Inherit from parent86 if (this.parent) return this.parent.engine;87 // Default88 return this.defaultEngine;89};9091/**92 * Resolve view path.93 *94 * @return {String}95 * @api private96 */9798View.prototype.resolvePath = function(){99 var path = this.view;100 // Implicit engine101 if (!~this.basename.indexOf('.')) path += this.extension;102 // Absolute103 if (utils.isAbsolute(path)) return path;104 // Relative to parent105 if (this.relative && this.parent) return this.parent.dirname + '/' + path;106 // Relative to root107 return this.root108 ? this.root + '/' + path109 : path;110};111112/**113 * Get view contents. This is a one-time hit, so we114 * can afford to be sync.115 *116 * @return {String}117 * @api public118 */119120View.prototype.__defineGetter__('contents', function(){121 return fs.readFileSync(this.path, 'utf8');122});123124/**125 * Get template engine api, cache exports to reduce126 * require() calls.127 *128 * @return {Object}129 * @api public130 */131132View.prototype.__defineGetter__('templateEngine', function(){133 var ext = this.extension;134 return cache[ext] || (cache[ext] = require(this.engine));135});136137/**138 * Return root path alternative.139 *140 * @return {String}141 * @api public142 */143144View.prototype.__defineGetter__('rootPath', function(){145 this.relative = false;146 return this.resolvePath();147});148149/**150 * Return index path alternative.151 *152 * @return {String}153 * @api public154 */155156View.prototype.__defineGetter__('indexPath', function(){157 return this.dirname158 + '/' + this.basename.replace(this.extension, '')159 + '/index' + this.extension;160});161162/**163 * Return ../<name>/index path alternative.164 *165 * @return {String}166 * @api public167 */168169View.prototype.__defineGetter__('upIndexPath', function(){170 return this.dirname + '/../' + this.name + '/index' + this.extension;171});172173/**174 * Return _ prefix path alternative175 *176 * @return {String}177 * @api public178 */179180View.prototype.__defineGetter__('prefixPath', function(){181 return this.dirname + '/_' + this.basename;182});183184/**185 * Register the given template engine `exports`186 * as `ext`. For example we may wish to map ".html"187 * files to jade:188 *189 * app.register('.html', require('jade'));190 *191 * or192 *193 * app.register('html', require('jade'));194 *195 * This is also useful for libraries that may not196 * match extensions correctly. For example my haml.js197 * library is installed from npm as "hamljs" so instead198 * of layout.hamljs, we can register the engine as ".haml":199 *200 * app.register('.haml', require('haml-js'));201 *202 * @param {String} ext203 * @param {Object} obj204 * @api public205 */206207exports.register = function(ext, exports) {208 if ('.' != ext[0]) ext = '.' + ext;209 cache[ext] = exports;210};
modified:lib/http.js+27 added-3 removed
58 unmodified lines
5960app.init = function(middleware){61 var self = this;62 this.cache = {};63 this.engines = {};64 this.settings = {};65 this.redirects = {};66 this.isCallbacks = {};67
210 unmodified lines
278 * @return {Server} for chaining279 * @api public280 */281281app.register = function(){282 view.register.apply(this, arguments);283 return this;282/**283 * Register the given template engine `exports`284 * as `ext`. For example we may wish to map ".html"285 * files to jade:286 *287 * app.register('.html', require('jade'));288 *289 * or290 *291 * app.register('html', require('jade'));292 *293 * This is also useful for libraries that may not294 * match extensions correctly. For example my haml.js295 * library is installed from npm as "hamljs" so instead296 * of layout.hamljs, we can register the engine as ".haml":297 *298 * app.register('.haml', require('haml-js'));299 *300 * @param {String} ext301 * @param {Object} obj302 * @api public303 */304305app.register = function(ext, exports) {306 if ('.' != ext[0]) ext = '.' + ext;307 this.engines[ext] = exports;308};309310/**311 * Map the given param placeholder `name`(s) to the given callback `fn`.
269 unmodified lines
modified:lib/proto.js+54 added
14 unmodified lines
15 , view = require('./view')16 , toArray = require('./utils').toArray17 , methods = router.methods.concat('del', 'all')18 , res = require('./response')19 , union = require('./utils').union20 , url = require('url')21 , utils = connect.utils22 , path = require('path')23 , extname = path.extname24 , join = path.join25 , fs = require('fs')26 , qs = require('qs');2728/**29 * Expose `HTTPServer`.
504 unmodified lines
534// del -> delete alias535536app.del = app.delete;537538/**539 * Render the given `view` name with `opts`540 * and a callback accepting an error and the541 * rendered template string.542 *543 * @param {String} view544 * @param {String|Function} opts or fn545 * @param {Function} fn546 * @api public547 */548549app.render = function(view, opts, fn){550 var self = this551 , options = {}552 , cache = this.cache553 , engines = this.engines554 , root = this.set('views') || process.cwd() + '/views';555556 // support callback function as second arg557 if ('function' == typeof opts) {558 fn = opts, opts = null;559 }560561 // merge app.locals562 union(options, this.locals);563564 // merge render() options565 if (opts) utils.merge(options, opts);566567 // join "view engine" if necessary568 var ext = extname(view);569 if (!ext) view += '.' + (ext = this.set('view engine'));570571 // pass .cache to the engine572 options.cache = this.enabled('view cache');573574 // when no extension nor "view engine" is given575 if (!ext) return fn(new Error('failed to find view "' + view + '"'));576577 // render578 try {579 var engine = cache[ext] = cache[ext] || require(ext);580 options.filename = join(root, view);581 view = fs.readFileSync(options.filename, 'utf8');582 engine.render(view, options, fn);583 } catch (err) {584 fn(err);585 }586};
modified:lib/view.js+44 added-376 removed
9 unmodified lines
10 */1112var path = require('path')13 , extname = path.extname14 , dirname = path.dirname15 , basename = path.basename14 , join = path.join15 , utils = require('connect').utils17 , View = require('./view/view')18 , partial = require('./view/partial')16 , union = require('./utils').union17 , merge = utils.merge18 , http = require('http')19 , fs = require('fs')20 , res = http.ServerResponse.prototype;2122/**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/**23 * Render `view` with the given `options` and optional callback `fn`.24 * When a callback function is given a response will _not_ be made294 * automatically, however otherwise a response of _200_ and _text/html_ is given.25 * automatically, otherwise a response of _200_ and _text/html_ is given.26 *27 * Options:28 * 298 * - `scope` Template evaluation context (the value of `this`)299 * - `debug` Output debugging information300 * - `status` Response status code29 * - `status` Response status code (`res.statusCode`)30 * - `charset` Set the charset (`res.charset`)31 *32 * Reserved locals:33 *34 * - `cache` boolean hinting to the engine it should cache35 * - `filename` filename of the view being rendered36 *37 * @param {String} view38 * @param {Object|Function} options or callback function39 * @param {Function} fn40 * @api public41 */42308res.render = function(view, opts, fn, parent, sub){43res.render = function(view, opts, fn){44 var self = this45 , options = {}46 , app = this.app47 , req = this.req48 , cache = app.cache49 , engines = app.engines50 , root = app.set('views') || process.cwd() + '/views';5152 // support callback function as second arg53 if ('function' == typeof opts) {54 fn = opts, opts = null;55 }56314 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;34257 // merge app.locals58 union(options, app.locals);5960 // merge res.locals
1 unmodified line
6263 // merge render() options64 if (opts) merge(options, opts);65352 // merge render() .locals353 if (opts && opts.locals) merge(options, opts.locals);35466 // status support67 if (options.status) this.statusCode = options.status;68358 // 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');38069 // charset option70 if (options.charset) this.charset = options.charset;71384 // Always expose partial() as a local385 options.partial = function(path, opts){386 return renderPartial(self, path, opts, options, view);387 };72 // join "view engine" if necessary73 var ext = extname(view);74 if (!ext) view += '.' + (ext = app.set('view engine'));75389 // View lookup390 options.hint = app.enabled('hints');391 view = exports.compile(view, app.cache, cid, options);76 // pass .cache to the engine77 options.cache = app.enabled('view cache');78393 // layout helper394 options.layout = function(path){395 layout = path;79 // when no extension nor "view engine" is given warn80 if (!ext) {81 console.warn('Warning: cannot determine view engine for "%s"', view);82 console.warn('provide the "view engine" setting or an');83 console.warn('extension such as "foo.jade".');84 return this.end();85 }8687 // callback88 fn = fn || function(err, str){89 if (err) return req.next(err);90 self.send(str);91 };9293 // 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);94 try {95 var engine = cache[ext] = cache[ext] || require(ext);96 options.filename = join(root, view);97 view = fs.readFileSync(options.filename, 'utf8');98 engine.render(view, options, fn);99 } catch (err) {100 fn(err);101 }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}102};
deleted:testing/index.js-15 removed
modified:.gitignore+2 added-1 removed
7 unmodified lines
8*.pid9*.swp10*.swo11benchmarks/graphs12testing.js12testing13node_modules/14testing
modified:package.json+1 added-1 removed