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
Provenance
- Commit
7710db4- Tree
0bd7c6a- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
ce03cf4
8 files changed+128 added−646 removed
deleted:lib/view/partial.js-40 removed
12345678910111213141516171819202122232425262728293031323334353637383940
/*! * Express - view - Partial * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */
/** * Memory cache. */
var cache = {};
/** * Resolve partial object name from the view path. * * Examples: * * "user.ejs" becomes "user" * "forum thread.ejs" becomes "forumThread" * "forum/thread/post.ejs" becomes "post" * "blog-post.ejs" becomes "blogPost" * * @return {String} * @api private */
exports.resolveObjectName = function(view){ return cache[view] || (cache[view] = view .split('/') .slice(-1)[0] .split('.')[0] .replace(/^_/, '') .replace(/[^a-zA-Z0-9 ]+/g, ' ') .split(/ +/).map(function(word, i){ return i ? word[0].toUpperCase() + word.substr(1) : word; }).join(''));};No newline at end of filedeleted:lib/view/view.js-210 removed
1-2-/*!3- * Express - View4- * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5- * MIT Licensed6- */7-8-/**9- * Module dependencies.10- */11-12-var path = require('path')13- , utils = require('../utils')14- , extname = path.extname15- , dirname = path.dirname16- , basename = path.basename17- , fs = require('fs')18- , stat = fs.statSync;19-20-/**21- * Expose `View`.22- */23-24-exports = module.exports = View;25-26-/**27- * Require cache.28- */29-30-var cache = {};31-32-/**33- * Initialize a new `View` with the given `view` path and `options`.34- *35- * @param {String} view36- * @param {Object} options37- * @api private38- */39-40-function 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-};58-59-/**60- * Check if the view path exists.61- *62- * @return {Boolean}63- * @api public64- */65-66-View.prototype.__defineGetter__('exists', function(){67- try {68- stat(this.path);69- return true;70- } catch (err) {71- return false;72- }73-});74-75-/**76- * Resolve view engine.77- *78- * @return {String}79- * @api private80- */81-82-View.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-};90-91-/**92- * Resolve view path.93- *94- * @return {String}95- * @api private96- */97-98-View.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-};111-112-/**113- * Get view contents. This is a one-time hit, so we114- * can afford to be sync.115- *116- * @return {String}117- * @api public118- */119-120-View.prototype.__defineGetter__('contents', function(){121- return fs.readFileSync(this.path, 'utf8');122-});123-124-/**125- * Get template engine api, cache exports to reduce126- * require() calls.127- *128- * @return {Object}129- * @api public130- */131-132-View.prototype.__defineGetter__('templateEngine', function(){133- var ext = this.extension;134- return cache[ext] || (cache[ext] = require(this.engine));135-});136-137-/**138- * Return root path alternative.139- *140- * @return {String}141- * @api public142- */143-144-View.prototype.__defineGetter__('rootPath', function(){145- this.relative = false;146- return this.resolvePath();147-});148-149-/**150- * Return index path alternative.151- *152- * @return {String}153- * @api public154- */155-156-View.prototype.__defineGetter__('indexPath', function(){157- return this.dirname158- + '/' + this.basename.replace(this.extension, '')159- + '/index' + this.extension;160-});161-162-/**163- * Return ../<name>/index path alternative.164- *165- * @return {String}166- * @api public167- */168-169-View.prototype.__defineGetter__('upIndexPath', function(){170- return this.dirname + '/../' + this.name + '/index' + this.extension;171-});172-173-/**174- * Return _ prefix path alternative175- *176- * @return {String}177- * @api public178- */179-180-View.prototype.__defineGetter__('prefixPath', function(){181- return this.dirname + '/_' + this.basename;182-});183-184-/**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- */206-207-exports.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 lines59 60 app.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 lines278 * @return {Server} for chaining279 * @api public280 */281 281-app.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+ */304+305+app.register = function(ext, exports) {306+ if ('.' != ext[0]) ext = '.' + ext;307+ this.engines[ext] = exports;308 };309 310 /**311 * Map the given param placeholder `name`(s) to the given callback `fn`.269 unmodified linesmodified:lib/proto.js+54 added
14 unmodified lines15 , 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');27 28 /**29 * Expose `HTTPServer`.504 unmodified lines534 // del -> delete alias535 536 app.del = app.delete;537 538+/**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+ */548+549+app.render = function(view, opts, fn){550+ var self = this551+ , options = {}552+ , cache = this.cache553+ , engines = this.engines554+ , root = this.set('views') || process.cwd() + '/views';555+556+ // support callback function as second arg557+ if ('function' == typeof opts) {558+ fn = opts, opts = null;559+ }560+561+ // merge app.locals562+ union(options, this.locals);563+564+ // merge render() options565+ if (opts) utils.merge(options, opts);566+567+ // join "view engine" if necessary568+ var ext = extname(view);569+ if (!ext) view += '.' + (ext = this.set('view engine'));570+571+ // pass .cache to the engine572+ options.cache = this.enabled('view cache');573+574+ // when no extension nor "view engine" is given575+ if (!ext) return fn(new Error('failed to find view "' + view + '"'));576+577+ // 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 lines10 */11 12 var 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;21 22 /**25- * Expose constructors.26- */27-28-exports = module.exports = View;29-30-/**31- * Export template engine registrar.32- */33-34-exports.register = View.register;35-36-/**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- */48-49-exports.compile = function(view, cache, cid, options){50- if (cache && cid && cache[cid]) return cache[cid];51-52- // lookup53- view = exports.lookup(view, options);54-55- // 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- } 62-63- // compile64- options.filename = view.path;65- view.fn = view.templateEngine.compile(view.contents, options);66- cache[cid] = view;67- 68- return view;69-};70-71-/**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- */95-96-exports.lookup = function(view, options){97- var orig = view = new View(view, options)98- , partial = options.isPartial99- , layout = options.isLayout;100-101- // 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- }107-108- // Try index ex: ./views/user/index.jade109- if (!layout && !view.exists) view = new View(orig.indexPath, options);110-111- // 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);114-115- // Try root ex: <root>/user.jade116- if (!view.exists) view = new View(orig.rootPath, options);117-118- // Try root _ prefix ex: <root>/_user.jade119- if (!view.exists && partial) view = new View(view.prefixPath, options);120-121- view.original = orig;122- return view;123-};124-125-/**126- * Partial render helper.127- *128- * @api private129- */130-131-function renderPartial(res, view, options, parentLocals, parent){132- var collection, object, locals;133-134- 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- }143-144- // locals145- if (options.locals) {146- locals = options.locals;147- delete options.locals;148- }149-150- // 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- }161-162- // Inherit locals from parent163- union(options, parentLocals);164- 165- // Merge locals166- if (locals) merge(options, locals);167-168- // Partials dont need layouts169- options.isPartial = true;170- options.layout = false;171-172- // Deduce name from view path173- var name = options.as || partial.resolveObjectName(view);174-175- // 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- }186-187- // Collection support188- if (collection) {189- var len = collection.length190- , buf = ''191- , keys192- , key193- , val;194-195- options.collectionLength = len;196-197- 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- }222-223- return buf;224- } else {225- return render();226- }227-};228-229-/**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- */252-253-res.partial = function(view, options, fn){254- var app = this.app255- , options = options || {}256- , viewEngine = app.set('view engine')257- , parent = {};258-259- // accept callback as second argument260- if ('function' == typeof options) {261- fn = options;262- options = {};263- }264-265- // root "views" option266- parent.dirname = app.set('views') || process.cwd() + '/views';267-268- // utilize "view engine" option269- if (viewEngine) parent.engine = viewEngine;270-271- // 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- }282-283- // callback or transfer284- if (fn) {285- fn(null, str);286- } else {287- this.send(str);288- }289-};290-291-/**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 */42 308-res.render = function(view, opts, fn, parent, sub){43+res.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';51+52 // support callback function as second arg53 if ('function' == typeof opts) {54 fn = opts, opts = null;55 }56 314- 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-};329-330-// private render()331-332-res._render = function(view, opts, fn, parent, sub){333- var options = {}334- , self = this335- , app = this.app336- , root = app.set('views') || process.cwd() + '/views';337-338- // cache id339- var cid = app.enabled('view cache')340- ? view + (parent ? ':' + parent.path : '')341- : false;342-57 // merge app.locals58 union(options, app.locals);59 60 // merge res.locals1 unmodified line62 63 // merge render() options64 if (opts) merge(options, opts);65 352- // merge render() .locals353- if (opts && opts.locals) merge(options, opts.locals);354-66 // status support67 if (options.status) this.statusCode = options.status;68 358- // capture attempts359- options.attempts = [];360-361- var partial = options.isPartial362- , layout = options.layout;363-364- // Layout support365- if (true === layout || undefined === layout) {366- layout = 'layout';367- }368-369- // Default execution scope to a plain object370- options.scope = options.scope || {};371-372- // Populate view373- options.parentView = parent;374-375- // "views" setting376- options.root = root;377-378- // "view engine" setting379- options.defaultEngine = app.set('view engine');380-69 // charset option70 if (options.charset) this.charset = options.charset;71 384- // 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'));75 389- // 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');78 393- // 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+ }86+87+ // callback88+ fn = fn || function(err, str){89+ if (err) return req.next(err);90+ self.send(str);91 };92 93 // render399- var str = view.fn.call(options.scope, options);400-401- // 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-}419-420-/**421- * Hint at view path resolution, outputting the422- * paths that Express has tried.423- *424- * @api private425- */426-427-function 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
123456789101112131415
/** * Module dependencies. */
var express = require('../') , http = require('http');
var app = express();
app.use(express.logger('dev'));app.use(express.static(__dirname));
http.createServer(app).listen(3000);console.log('listening on port 3000');No newline at end of filemodified:.gitignore+2 added-1 removed
7 unmodified lines8 *.pid9 *.swp10 *.swo11 benchmarks/graphs12-testing.js12+testing13 node_modules/14+testingmodified:package.json+1 added-1 removed
19 unmodified lines202122232424252627289 unmodified lines19 unmodified lines "connect-form": "0.2.1", "ejs": "0.4.2", "expresso": "0.8.1", "hamljs": "0.5.1", "jade": "0.13.0", "jade": "0.16.2", "stylus": "0.13.0", "should": "0.2.1", "express-messages": "0.0.2", "node-markdown": ">= 0.0.1",9 unmodified lines