Rinser/node_modules/express/lib/view.js

78 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-07-20 13:42:07 +00:00
/**
* Module dependencies.
*/
2015-08-14 19:58:05 +00:00
var path = require('path')
, fs = require('fs')
, utils = require('./utils')
, dirname = path.dirname
, basename = path.basename
, extname = path.extname
, exists = fs.existsSync || path.existsSync
, join = path.join;
2015-07-20 13:42:07 +00:00
/**
2015-08-14 19:58:05 +00:00
* Expose `View`.
2015-07-20 13:42:07 +00:00
*/
module.exports = View;
/**
* Initialize a new `View` with the given `name`.
*
* Options:
*
* - `defaultEngine` the default template engine name
* - `engines` template engine require() cache
* - `root` root path for view lookup
*
2015-08-14 19:58:05 +00:00
* @param {String} name
* @param {Object} options
* @api private
2015-07-20 13:42:07 +00:00
*/
function View(name, options) {
2015-08-14 19:58:05 +00:00
options = options || {};
2015-07-20 13:42:07 +00:00
this.name = name;
2015-08-14 19:58:05 +00:00
this.root = options.root;
var engines = options.engines;
this.defaultEngine = options.defaultEngine;
var ext = this.ext = extname(name);
if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
this.path = this.lookup(name);
2015-07-20 13:42:07 +00:00
}
/**
2015-08-14 19:58:05 +00:00
* Lookup view by the given `path`
2015-07-20 13:42:07 +00:00
*
2015-08-14 19:58:05 +00:00
* @param {String} path
* @return {String}
* @api private
2015-07-20 13:42:07 +00:00
*/
2015-08-14 19:58:05 +00:00
View.prototype.lookup = function(path){
2015-07-20 13:42:07 +00:00
var ext = this.ext;
2015-08-14 19:58:05 +00:00
// <path>.<engine>
if (!utils.isAbsolute(path)) path = join(this.root, path);
if (exists(path)) return path;
2015-07-20 13:42:07 +00:00
2015-08-14 19:58:05 +00:00
// <path>/index.<engine>
path = join(dirname(path), basename(path, ext), 'index' + ext);
if (exists(path)) return path;
2015-07-20 13:42:07 +00:00
};
/**
2015-08-14 19:58:05 +00:00
* Render with the given `options` and callback `fn(err, str)`.
2015-07-20 13:42:07 +00:00
*
2015-08-14 19:58:05 +00:00
* @param {Object} options
* @param {Function} fn
* @api private
2015-07-20 13:42:07 +00:00
*/
2015-08-14 19:58:05 +00:00
View.prototype.render = function(options, fn){
this.engine(this.path, options, fn);
};