Utilizing the new View / Partial constructors
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 9f4b736 · Browse files · 26 files·+175 added−165 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
26 files+175 added−165 removed
- tests:+69 added−68 removed
- other:+106 added−97 removed
Provenance
- Commit
ad32441- Tree
467868b- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
9f4b736
26 files changed+175 added−165 removed
modified:lib/express/utils.js+16 added
41 unmodified lines42434445464748495051525354555657585960616263646527 unmodified lines41 unmodified lines .replace(/>/g, '>');};
/** * Clone `obj`. * * @param {Object} obj * @return {Object} * @api private */
exports.clone = function(obj){ var ret = {}; for (var key in obj) { ret[key] = obj[key]; } return ret;};
/** * Parse "Range" header `str` relative to the given file `size`. * * @param {Number} size * @param {String} str27 unmodified linesmodified:lib/express/view.js+90 added-97 removed
11 unmodified lines12 var extname = require('path').extname13 , dirname = require('path').dirname14 , basename = require('path').basename15 , utils = require('connect').utils16+ , clone = require('./utils').clone17+ , merge = utils.merge18 , http = require('http')19 , fs = require('fs')20 , mime = utils.mime;21 21 unmodified lines43 44 var viewNameCache = {};45 46 /**45- * Initialize a new `View` with the given `view` path,46- * `options` and callback `fn`.47+ * Initialize a new `View` with the given `view` path and `options`.48 *49 * @param {String} view50 * @param {Object} options50- * @param {Function} fn51 * @api private52 */53 54-var View = exports = module.exports = function View(view, options, fn) {54+var View = exports = module.exports = function View(view, options) {55 options = options || {};56 // TODO: memoize basename etc57 this.view = view;58- this.fn = fn;58 this.root = options.root;60- this.partial = options.partial;61- this.defaultEngine = options.defaultViewEngine;59+ this.defaultEngine = options.defaultEngine;60 this.parent = options.parentView;61 this.basename = basename(view);62 this.engine = this.resolveEngine();63 this.extension = '.' + this.engine;64 this.path = this.resolvePath();65 this.dirname = dirname(this.path);68- if (this.partial) {69- this.objectName = options.as || this.resolveObjectName();70- this.path = this.dirname + '/_' + basename(this.path);71- }66 };67 68 /**69 * Resolve view engine.32 unmodified lines102 : path;103 };104 105 /**106+ * Get view contents. This is a one-time hit, so we107+ * can afford to be sync.108+ *109+ * @return {String}110+ * @api public111+ */112+113+View.prototype.__defineGetter__('contents', function(){114+ return fs.readFileSync(this.path, 'utf8');115+});116+117+/**118+ * Get template engine api, cache exports to reduce119+ * require() calls.120+ *121+ * @return {Object}122+ * @api public123+ */124+125+View.prototype.__defineGetter__('templateEngine', function(){126+ var ext = this.extension;127+ return cache[ext]128+ || (cache[ext] = require(this.engine));129+});130+131+/**132+ * Initialize a new `Partial` for the given `view` and `options`.133+ *134+ * @param {String} view135+ * @param {Object} options136+ * @api private137+ */138+139+var Partial = exports.Partial = function Partial(view, options) {140+ options = options || {};141+ View.call(this, view, options);142+ this.objectName = options.as || this.resolveObjectName();143+ this.path = this.dirname + '/_' + basename(this.path);144+};145+146+/**147+ * Inherit from `View.prototype`.148+ */149+150+Partial.prototype.__proto__ = View.prototype;151+152+/**153 * Resolve partial object name from the view path.154 *155 * Examples:156 *5 unmodified lines162 * @return {String}163 * @api private164 */165 125-View.prototype.resolveObjectName = function(){166+Partial.prototype.resolveObjectName = function(){167 // TODO: cache168 return this.view169 .split('/')170 .slice(-1)[0]6 unmodified lines177 }).join('');178 };179 180 /**140- * Get view contents. This is a one-time hit, so we141- * can afford to be sync.142- *143- * @return {String}144- * @api public145- */146-147-View.prototype.__defineGetter__('contents', function(){148- return fs.readFileSync(this.view, 'utf8');149-});150-151-/**152- * Get template engine api, cache exports to reduce153- * require() calls.154- *155- * @return {Object}156- * @api public157- */158-159-View.prototype.__defineGetter__('templateEngine', function(){160- var engine = this.engine;161- return cache[engine]162- || (cache[engine] = require(engine))163-});164-165-/**181 * Synchronously cache view at the given `path`.182 *183 * @param {String} path184 * @return {String}87 unmodified lines272 * @return {String}273 * @api public274 */275 261-http.ServerResponse.prototype.partial = function(view, options, ext, locals){276+http.ServerResponse.prototype.partial = function(view, options, locals, parent){277 locals = locals || {};278 279 // Inherit parent view extension when not present265- if (ext && view.indexOf('.') < 0) {266- view += ext;280+ if (parent && !~view.indexOf('.')) {281+ view += parent.extension;282 }283 284 // Allow collection to be passed as second param285 if (options) {7 unmodified lines293 }294 295 // Inherit locals from parent296 options.locals = options.locals282- ? utils.merge(locals, options.locals)297+ ? merge(locals, options.locals)298 : locals;299 300 // Partials dont need layouts286- options.partial = true;301+ options.renderPartial = true;302 options.layout = false;303 304 // Deduce name from view path305 var name = options.as20 unmodified lines326 if (options.object) {327 if ('string' == typeof name) {328 options.locals[name] = options.object;329 } else if (name === global) {315- utils.merge(options.locals, options.object);330+ merge(options.locals, options.object);331 } else {332 options.scope = options.object;333 }334 }11 unmodified lines346 * Most engines accept one or more of the following options,347 * both _haml_ and _jade_ accept all:348 *349 * - `scope` Template evaluation context (the value of `this`)335- * - `locals` Object containing local variables350 * - `debug` Output debugging information351 * - `status` Response status code, defaults to 200352 * - `headers` Response headers object353 *2 unmodified lines356 * @param {Function} fn357 * @api public358 */359 346-http.ServerResponse.prototype.render = function(view, options, fn){360+http.ServerResponse.prototype.render = function(view, options, fn, parent){361 // Support callback function as second arg362 if (typeof options === 'function') {363 fn = options, options = {};364 }365 352- var options = options || {}366+ var self = this367 , app = this.app354- , viewOptions = app.settings['view options']355- , defaultEngine = app.settings['view engine'];368+ , options = options || {}369+ , helpers = app.viewHelpers370+ , dynamicHelpers = app.dynamicViewHelpers371+ , viewOptions = app.settings['view options'];372 373 // Mixin "view options"374 if (viewOptions) options.__proto__ = viewOptions;375 360- // Support "view engine" setting361- if (view.indexOf('.') < 0 && defaultEngine) {362- view += '.' + defaultEngine;363- }364-376 // Defaults377 var self = this367- , helpers = this.app.viewHelpers368- , dynamicHelpers = this.app.dynamicViewHelpers378 , root = viewRoot(this.app)370- , ext = extname(view)371- , partial = options.partial372- , layout = options.layout === undefined ? true : options.layout379+ , partial = options.renderPartial380+ , layout = options.layout;373- , layout = layout === true374- ? 'layout' + ext375- : layout;381 377- // Allow layout name without extension378- if (typeof layout === 'string' && layout.indexOf('.') < 0) {379- layout += ext;382+ // Layout support383+ if (true === layout || undefined === layout) {384+ layout = 'layout';385 }386 387 // Default execution scope to the response388 options.scope = options.scope || this.req;389 385- // Auto-cache in production386- if ('production' == app.settings.env) {387- options.cache = true;388- }390+ // Pass filename to the engine and view391+ var locals = options.locals = options.locals || {};392 390- // Partials support391- if (options.partial) {392- root = app.settings.partials || root + '/partials';393- }393+ // Populate view394+ options.parentView = parent;395 395- // View path396- var path = view[0] === '/'397- ? view398- : root + '/' + view;396+ // "views" setting397+ options.root = app.settings.views || process.cwd() + '/views';398 400- // Pass filename to the engine and view401- var locals = options.locals = options.locals || {};402- options.locals.__filename = options.filename = path;399+ // "view engine" setting400+ options.defaultEngine = app.settings['view engine'];401 402+ // Populate view403+ view = partial404+ ? new Partial(view, options)405+ : new View(view, options);406+407 // Dynamic helper support408 if (false !== options.dynamicHelpers) {409 // cache410 if (!this.__dynamicHelpers) {11 unmodified lines422 }423 }424 425 // apply423- helpers.__proto__ = this.__dynamicHelpers;426+ merge(options.locals, this.__dynamicHelpers);427 }428 429 // Merge view helpers427- options.locals.__proto__ = helpers;430+ options.locals = merge(clone(helpers), options.locals);431 432 // Always expose partial() as a local430- options.locals.partial = function(view, options){431- return self.partial.call(self, view, options, ext, locals);433+ options.locals.partial = function(path, options){434+ return self.partial(path, options, locals, view);435 };436 437 function error(err) {438 if (fn) {2 unmodified lines441 self.req.next(err);442 }443 }444 442- // Cache contents443- try {444- var str = (options.cache ? viewCache[path] : null) || cacheViewSync(path);445- } catch (err) {446- return error(err);447- }448-449- // Cache template engine exports450- var engine = cache[ext] || (cache[ext] = require(ext.substr(1)));451-445 // Attempt render446 try {454- var str = engine.render(str, options);447+ var template = view.templateEngine.compile(view.contents, options);448+ str = template.call(options.scope, options.locals);449 } catch (err) {450 return error(err);451 }452 453 // Layout support454 if (layout) {455 options.layout = false;456 options.locals.body = str;463- options.isLayout = true;464- self.render(layout, options, fn);457+ self.render(layout, options, fn, view);458 } else if (partial) {459 return str;460 } else if (fn) {461 fn(null, str);4 unmodified linesmodified:support/shouldnot shown
Its text is not shown, modified.
deleted:test/fixtures/partials/user/role.ejs-1 removed
1-<li>Role: <%= role %></li>deleted:test/fixtures/partials/greetings.jade-1 removed
1-p Welcome #{name}deleted:test/fixtures/partials/hello.ejs-1 removed
1-Hellodeleted:test/fixtures/partials/item.jade-1 removed
1-li= itemdeleted:test/fixtures/partials/magic.jade-6 removed
1-- if (firstInCollection)2- li.first= word3-- else if (lastInCollection)4- li.last= word5-- else6- li(class: 'word-' + indexInCollection)= worddeleted:test/fixtures/partials/movie.jade-3 removed
1-li2- .title= movie.title3- .director= movie.directordeleted:test/fixtures/partials/person.jade-1 removed
1-p #{label} #{this.name}deleted:test/fixtures/partials/pet-count.jade-1 removed
1-| We have #{pets.length} cool petsdeleted:test/fixtures/partials/pet.jade-4 removed
1-- if (firstInCollection)2- li #{pet} is the coolest of #{site}3-- else4- li= petdeleted:test/fixtures/partials/user.jade-1 removed
1-p= person.namedeleted:test/fixtures/partials/video.jade-1 removed
1-p= directoradded:test/fixtures/user/_role.ejs+1 added
1+<li>Role: <%= role %></li>added:test/fixtures/_greetings.jade+1 added
1+p Welcome #{name}added:test/fixtures/_hello.ejs+1 added
1+Helloadded:test/fixtures/_item.jade+1 added
1+li= itemadded:test/fixtures/_magic.jade+6 added
1+- if (firstInCollection)2+ li.first= word3+- else if (lastInCollection)4+ li.last= word5+- else6+ li(class: 'word-' + indexInCollection)= wordadded:test/fixtures/_movie.jade+3 added
1+li2+ .title= movie.title3+ .director= movie.directoradded:test/fixtures/_person.jade+1 added
1+p #{label} #{this.name}added:test/fixtures/_pet-count.jade+1 added
1+| We have #{pets.length} cool petsadded:test/fixtures/_pet.jade+4 added
1+- if (firstInCollection)2+ li #{pet} is the coolest of #{site}3+- else4+ li= petadded:test/fixtures/_user.jade+1 added
1+p= person.nameadded:test/fixtures/_video.jade+1 added
1+p= directormodified:test/view.test.js+48 added-47 removed
5 unmodified lines6 var express = require('express')7 , connect = require('connect')8 , assert = require('assert')9 , should = require('should')10- , View = require('express/view');10+ , View = require('express/view')11+ , Partial = View.Partial12 13 /**14 * Create a test server with views set to ./fixtures.15 */30 unmodified lines46 var view = new View('user', { parentView: view });47 view.path.should.equal('/foo.bar.baz/user.ejs');48 },49 49- 'test View#path for partials': function(){50- var view = new View('user.ejs', { root: '/www', partial: true });51- view.path.should.equal('/www/_user.ejs');52-53- var view = new View('user', { parentView: view, root: '/www', partial: true });54- view.path.should.equal('/www/_user.ejs');55- 56- var view = new View('forum/thread', { parentView: view, partial: true });57- view.path.should.equal('/www/forum/_thread.ejs');58-59- var view = new View('forum/thread.jade', { root: '/www', partial: true });60- view.path.should.equal('/www/forum/_thread.jade');61- },62- 50 'test View#engine': function(){51 var view = new View('/absolute/path.ejs');52 view.engine.should.equal('ejs');53 54 var view = new View('user', { parentView: view });55 view.engine.should.equal('ejs');56 70- var view = new View('/user', { defaultViewEngine: 'jade' });57+ var view = new View('/user', { defaultEngine: 'jade' });58 view.engine.should.equal('jade');59 60 var view = new View('/foo.bar/user.ejs');61 view.engine.should.equal('ejs');5 unmodified lines67 68 var view = new View('user', { parentView: view });69 view.extension.should.equal('.ejs');70 84- var view = new View('/user', { defaultViewEngine: 'jade' });71+ var view = new View('/user', { defaultEngine: 'jade' });72 view.extension.should.equal('.jade');73 74 var view = new View('/foo.bar/user.ejs');75 view.extension.should.equal('.ejs');6 unmodified lines82 var view = new View('user', { parentView: view });83 view.dirname.should.equal('/absolute');84 },85 99- 'test View#objectName': function(){100- var view = new View('/path/to/user.ejs', { partial: true });86+ 'test View#contents': function(){87+ var view = new View(__dirname + '/fixtures/hello.jade');88+ view.contents.should.equal('p :(');89+ },90+ 91+ 'test View#templateEngine': function(){92+ var view = new View(__dirname + '/fixtures/hello.jade');93+ view.templateEngine.should.equal(require('jade'));94+ },95+ 96+ 'test Partial#objectName': function(){97+ var view = new Partial('/path/to/user.ejs');98 view.objectName.should.equal('user');99 103- var view = new View('/path/to/user-post.ejs', { partial: true });100+ var view = new Partial('/path/to/user-post.ejs');101 view.objectName.should.equal('userPost');102 106- var view = new View('/path/to/user_post.ejs', { partial: true });103+ var view = new Partial('/path/to/user_post.ejs');104 view.objectName.should.equal('userPost');105 109- var view = new View('/path/to/forum thread post.ejs', { partial: true });106+ var view = new Partial('/path/to/forum thread post.ejs');107 view.objectName.should.equal('forumThreadPost');108 112- var view = new View('/path/to/forum thread post.ejs', { as: 'post', partial: true });109+ var view = new Partial('/path/to/forum thread post.ejs', { as: 'post' });110 view.objectName.should.equal('post');111 },112 116- 'test View#contents': function(){117- var view = new View(__dirname + '/fixtures/hello.jade');118- view.contents.should.equal('p :(');113+ 'test Partial#path for partials': function(){114+ var view = new Partial('user.ejs', { root: '/www' });115+ view.path.should.equal('/www/_user.ejs');116+117+ var view = new Partial('user', { parentView: view, root: '/www' });118+ view.path.should.equal('/www/_user.ejs');119+ 120+ var view = new Partial('forum/thread', { parentView: view });121+ view.path.should.equal('/www/forum/_thread.ejs');122+123+ var view = new Partial('forum/thread.jade', { root: '/www' });124+ view.path.should.equal('/www/forum/_thread.jade');125 },120- 121- 'test View#templateEngine': function(){122- var view = new View(__dirname + '/fixtures/hello.jade');123- view.templateEngine.should.equal(require('jade'));124- },126 127 'test #render()': function(){128 var app = create();129 app.set('view engine', 'jade');5 unmodified lines135 app.get('/jade', function(req, res){136 res.render('index', { layout: false });137 });138 138- app.get('/haml', function(req, res){139- res.render('hello.haml', { layout: false });140- });139+ // app.get('/haml', function(req, res){140+ // res.render('hello.haml', { layout: false });141+ // });142 143 app.get('/callback/layout/no-options', function(req, res){144 res.render('hello.jade', function(err, str){145 assert.ok(!err);7 unmodified lines153 res.send(str.replace(':(', ':)'));154 });155 });156 156- app.get('/callback', function(req, res){157- res.render('hello.haml', { layout: false }, function(err, str){158- assert.ok(!err);159- res.send(str.replace('Hello World', ':)'));160- });161- });157+ // app.get('/callback', function(req, res){158+ // res.render('hello.haml', { layout: false }, function(err, str){159+ // assert.ok(!err);160+ // res.send(str.replace('Hello World', ':)'));161+ // });162+ // });163 164 app.get('/invalid', function(req, res){165 res.render('invalid.jade', { layout: false });166 });22 unmodified lines189 { body: '<p>Welcome</p>' });190 assert.response(app,191 { url: '/absolute' },192 { body: '<p>Welcome</p>' });193+ // assert.response(app,194+ // { url: '/haml' },195+ // { body: '\n<p>Hello World</p>' });196+ // assert.response(app,197+ // { url: '/callback' },198+ // { body: '\n<p>:)</p>' });199 assert.response(app,193- { url: '/haml' },194- { body: '\n<p>Hello World</p>' });195- assert.response(app,196- { url: '/callback' },197- { body: '\n<p>:)</p>' });198- assert.response(app,200 { url: '/callback/layout' },201 { body: '<html><body><p>:)</p></body></html>' });202 assert.response(app,203 { url: '/callback/layout/no-options' },527 unmodified lines731 });732 733 assert.response(app,734 { url: '/' },734- { body: '<ul><li class="item">foo</li><li class="item">bar</li></ul>' });735+ { body: '<ul><li>foo</li><li>bar</li></ul>' });736 },737 738 'test "view options"': function(){739 var app = create();48 unmodified lines