Skip to content
Myr

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

26 files+175 added−165 removed

modified:lib/express/utils.js+16 added
modified:lib/express/view.js+90 added-97 removed
11 unmodified lines
12var 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 lines
4344var viewNameCache = {};4546/**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 */5354var View = exports = module.exports = function View(view, options, fn) {54var 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};6768/**69 * Resolve view engine.
32 unmodified lines
102 : path;103};104105/**106 * Get view contents. This is a one-time hit, so we107 * can afford to be sync.108 *109 * @return {String}110 * @api public111 */112113View.prototype.__defineGetter__('contents', function(){114 return fs.readFileSync(this.path, 'utf8');115});116117/**118 * Get template engine api, cache exports to reduce119 * require() calls.120 *121 * @return {Object}122 * @api public123 */124125View.prototype.__defineGetter__('templateEngine', function(){126 var ext = this.extension;127 return cache[ext]128 || (cache[ext] = require(this.engine));129});130131/**132 * Initialize a new `Partial` for the given `view` and `options`.133 *134 * @param {String} view135 * @param {Object} options136 * @api private137 */138139var 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};145146/**147 * Inherit from `View.prototype`.148 */149150Partial.prototype.__proto__ = View.prototype;151152/**153 * Resolve partial object name from the view path.154 *155 * Examples:156 *
5 unmodified lines
162 * @return {String}163 * @api private164 */165125View.prototype.resolveObjectName = function(){166Partial.prototype.resolveObjectName = function(){167 // TODO: cache168 return this.view169 .split('/')170 .slice(-1)[0]
6 unmodified lines
177 }).join('');178};179180/**140 * Get view contents. This is a one-time hit, so we141 * can afford to be sync.142 *143 * @return {String}144 * @api public145 */146147View.prototype.__defineGetter__('contents', function(){148 return fs.readFileSync(this.view, 'utf8');149});150151/**152 * Get template engine api, cache exports to reduce153 * require() calls.154 *155 * @return {Object}156 * @api public157 */158159View.prototype.__defineGetter__('templateEngine', function(){160 var engine = this.engine;161 return cache[engine]162 || (cache[engine] = require(engine))163});164165/**181 * Synchronously cache view at the given `path`.182 *183 * @param {String} path184 * @return {String}
87 unmodified lines
272 * @return {String}273 * @api public274 */275261http.ServerResponse.prototype.partial = function(view, options, ext, locals){276http.ServerResponse.prototype.partial = function(view, options, locals, parent){277 locals = locals || {};278279 // 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 }283284 // Allow collection to be passed as second param285 if (options) {
7 unmodified lines
293 }294295 // Inherit locals from parent296 options.locals = options.locals282 ? utils.merge(locals, options.locals)297 ? merge(locals, options.locals)298 : locals;299300 // Partials dont need layouts286 options.partial = true;301 options.renderPartial = true;302 options.layout = false;303304 // Deduce name from view path305 var name = options.as
20 unmodified lines
326 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 lines
346 * 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 lines
356 * @param {Function} fn357 * @api public358 */359346http.ServerResponse.prototype.render = function(view, options, fn){360http.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'];372373 // Mixin "view options"374 if (viewOptions) options.__proto__ = viewOptions;375360 // Support "view engine" setting361 if (view.indexOf('.') < 0 && defaultEngine) {362 view += '.' + defaultEngine;363 }364376 // 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;381377 // 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 }386387 // Default execution scope to the response388 options.scope = options.scope || this.req;389385 // 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 || {};392390 // Partials support391 if (options.partial) {392 root = app.settings.partials || root + '/partials';393 }393 // Populate view394 options.parentView = parent;395395 // View path396 var path = view[0] === '/'397 ? view398 : root + '/' + view;396 // "views" setting397 options.root = app.settings.views || process.cwd() + '/views';398400 // 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'];401402 // Populate view403 view = partial404 ? new Partial(view, options)405 : new View(view, options);406407 // Dynamic helper support408 if (false !== options.dynamicHelpers) {409 // cache410 if (!this.__dynamicHelpers) {
11 unmodified lines
422 }423 }424425 // apply423 helpers.__proto__ = this.__dynamicHelpers;426 merge(options.locals, this.__dynamicHelpers);427 }428429 // Merge view helpers427 options.locals.__proto__ = helpers;430 options.locals = merge(clone(helpers), options.locals);431432 // 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 };436437 function error(err) {438 if (fn) {
2 unmodified lines
441 self.req.next(err);442 }443 }444442 // Cache contents443 try {444 var str = (options.cache ? viewCache[path] : null) || cacheViewSync(path);445 } catch (err) {446 return error(err);447 }448449 // Cache template engine exports450 var engine = cache[ext] || (cache[ext] = require(ext.substr(1)));451445 // 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 }452453 // 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 lines
modified: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
1p Welcome #{name}
deleted:test/fixtures/partials/hello.ejs-1 removed
1Hello
deleted:test/fixtures/partials/item.jade-1 removed
1li= item
deleted: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)= word
deleted:test/fixtures/partials/movie.jade-3 removed
1li2 .title= movie.title3 .director= movie.director
deleted:test/fixtures/partials/person.jade-1 removed
1p #{label} #{this.name}
deleted:test/fixtures/partials/pet-count.jade-1 removed
1| We have #{pets.length} cool pets
deleted:test/fixtures/partials/pet.jade-4 removed
1- if (firstInCollection)2 li #{pet} is the coolest of #{site}3- else4 li= pet
deleted:test/fixtures/partials/user.jade-1 removed
1p= person.name
deleted:test/fixtures/partials/video.jade-1 removed
1p= director
added:test/fixtures/user/_role.ejs+1 added
1<li>Role: <%= role %></li>
added:test/fixtures/_greetings.jade+1 added
1p Welcome #{name}
added:test/fixtures/_hello.ejs+1 added
1Hello
added:test/fixtures/_item.jade+1 added
1li= item
added: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)= word
added:test/fixtures/_movie.jade+3 added
1li2 .title= movie.title3 .director= movie.director
added:test/fixtures/_person.jade+1 added
1p #{label} #{this.name}
added:test/fixtures/_pet-count.jade+1 added
1| We have #{pets.length} cool pets
added:test/fixtures/_pet.jade+4 added
1- if (firstInCollection)2 li #{pet} is the coolest of #{site}3- else4 li= pet
added:test/fixtures/_user.jade+1 added
1p= person.name
added:test/fixtures/_video.jade+1 added
1p= director
modified:test/view.test.js+48 added-47 removed
5 unmodified lines
6var 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.Partial1213/**14 * Create a test server with views set to ./fixtures.15 */
30 unmodified lines
46 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');5253 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');5859 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');5354 var view = new View('user', { parentView: view });55 view.engine.should.equal('ejs');5670 var view = new View('/user', { defaultViewEngine: 'jade' });57 var view = new View('/user', { defaultEngine: 'jade' });58 view.engine.should.equal('jade');5960 var view = new View('/foo.bar/user.ejs');61 view.engine.should.equal('ejs');
5 unmodified lines
6768 var view = new View('user', { parentView: view });69 view.extension.should.equal('.ejs');7084 var view = new View('/user', { defaultViewEngine: 'jade' });71 var view = new View('/user', { defaultEngine: 'jade' });72 view.extension.should.equal('.jade');7374 var view = new View('/foo.bar/user.ejs');75 view.extension.should.equal('.ejs');
6 unmodified lines
82 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');99103 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');102106 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');105109 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');116117 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');122123 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 },126127 'test #render()': function(){128 var app = create();129 app.set('view engine', 'jade');
5 unmodified lines
135 app.get('/jade', function(req, res){136 res.render('index', { layout: false });137 });138138 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 // });142143 app.get('/callback/layout/no-options', function(req, res){144 res.render('hello.jade', function(err, str){145 assert.ok(!err);
7 unmodified lines
153 res.send(str.replace(':(', ':)'));154 });155 });156156 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 // });163164 app.get('/invalid', function(req, res){165 res.render('invalid.jade', { layout: false });166 });
22 unmodified lines
189 { 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 lines
731 });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