2 * EJS Embedded JavaScript templates
3 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
21 var fs = require('fs')
22 , utils = require('./utils')
24 , _VERSION_STRING = require('../package.json').version
25 , _DEFAULT_DELIMITER = '%'
26 , _DEFAULT_LOCALS_NAME = 'locals'
27 , _REGEX_STRING = '(<%%|<%=|<%-|<%#|<%|%>|-%>)'
28 , _OPTS = [ 'cache', 'filename', 'delimiter', 'scope', 'context'
29 , 'debug', 'compileDebug', 'client', '_with'
31 , _TRAILING_SEMCOL = /;\s*$/;
33 exports.localsName = _DEFAULT_LOCALS_NAME;
35 exports.resolveInclude = function(name, filename) {
36 var path = require('path')
37 , dirname = path.dirname
38 , extname = path.extname
39 , resolve = path.resolve
40 , includePath = resolve(dirname(filename), name)
41 , ext = extname(name);
43 includePath += '.ejs';
49 // Returns a possibly cached template function, set by options.cache.
50 // `template` is the string of EJS to compile.
51 // If template is undefined then the file specified in options.filename is
53 function handleCache(options, template) {
55 , path = options.filename
56 , hasTemplate = template !== undefined;
60 throw new Error('cache option requires a filename');
67 template = fs.readFileSync(path, {encoding: 'utf8'});
70 else if (!hasTemplate) {
72 throw new Error('Internal EJS error: no file name or template '
75 template = fs.readFileSync(path, {encoding: 'utf8'});
77 fn = exports.compile(template.trim(), options);
84 function includeFile(path, options) {
85 var opts = utils.shallowCopy({}, options || /* istanbul ignore next */ {});
87 throw new Error('`include` requires the \'filename\' option.');
89 opts.filename = exports.resolveInclude(path, opts.filename);
90 return handleCache(opts);
93 function includeSource(path, options) {
94 var opts = utils.shallowCopy({}, options || {})
98 throw new Error('`include` requires the \'filename\' option.');
100 includePath = exports.resolveInclude(path, opts.filename);
101 template = fs.readFileSync(includePath).toString().trim();
103 opts.filename = includePath;
104 var templ = new Template(template, opts);
105 templ.generateSource();
109 function rethrow(err, str, filename, lineno){
110 var lines = str.split('\n')
111 , start = Math.max(lineno - 3, 0)
112 , end = Math.min(lines.length, lineno + 3);
115 var context = lines.slice(start, end).map(function (line, i){
116 var curr = i + start + 1;
117 return (curr == lineno ? ' >> ' : ' ')
123 // Alter exception message
125 err.message = (filename || 'ejs') + ':'
133 function cpOptsInData(data, opts) {
134 _OPTS.forEach(function (p) {
135 if (typeof data[p] != 'undefined') {
139 delete data.__expressRender__;
142 function compile(template, opts) {
146 // 'scope' is 'context'
147 // FIXME: Remove this in a future version
148 if (opts && opts.scope) {
150 opts.context = opts.scope;
154 templ = new Template(template, opts);
155 return templ.compile();
157 exports.compile = compile;
159 // template, [data], [opts]
160 // Have to include an empty data object if you want opts and no data
161 exports.render = function (template, data, opts) {
166 // No options object -- if there are optiony names
167 // in the data, copy them to options
168 if (arguments.length == 2) {
169 cpOptsInData(data, opts);
172 fn = handleCache(opts, template);
173 return fn.call(opts.context, data);
176 // path, [data], [opts], cb
177 // Have to include an empty data object if you want opts and no data
178 exports.renderFile = function () {
179 var args = Array.prototype.slice.call(arguments)
180 , path = args.shift()
182 , data = args.shift() || {}
183 , opts = args.pop() || {}
187 // No options object -- if there are optiony names
188 // in the data, copy them to options
189 if (arguments.length == 3) {
190 cpOptsInData(data, opts);
192 opts.filename = path;
195 result = handleCache(opts)(data);
198 return process.nextTick(function () {
202 process.nextTick(function () {
207 exports.clearCache = function () {
211 function Template(text, opts) {
214 this.templateText = text;
216 this.truncate = false;
217 this.currentLine = 1;
219 options.client = opts.client || false;
220 options.escapeFunction = opts.escape || utils.escapeXML;
221 options.compileDebug = opts.compileDebug !== false;
222 options.debug = !!opts.debug;
223 options.filename = opts.filename;
224 options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
225 options._with = typeof opts._with != 'undefined' ? opts._with : true;
226 options.cache = opts.cache || false;
229 this.regex = this.createRegex();
240 Template.prototype = new function () {
241 this.createRegex = function () {
242 var str = _REGEX_STRING
243 , delim = utils.escapeRegExpChars(this.opts.delimiter);
244 str = str.replace(/%/g, delim);
245 return new RegExp(str);
248 this.compile = function () {
252 , escape = opts.escapeFunction;
255 this.generateSource();
256 var prepended = 'var __output = [];';
257 if (opts._with !== false) {
258 prepended += ' with (' + exports.localsName + ' || {}) { ';
260 this.source = prepended + this.source;
261 if (opts._with !== false) {
264 this.source += ';return __output.join("").trim();';
267 if (opts.compileDebug) {
268 src = 'var __line = 1' +
269 ', __lines = ' + JSON.stringify(this.templateText) +
270 ', __filename = ' + (opts.filename ?
271 JSON.stringify(opts.filename) : 'undefined') +
273 this.source + '} catch (e) { rethrow(e, __lines, __filename, __line); }';
284 if (escape !== utils.escapeXML) {
285 src = 'escape = escape || ' + escape.toString() + ';\n' + src;
288 src = utils.escapeFuncStr
289 + 'escape = escape || '
290 + escape.toString() + ';\n'
293 if (opts.compileDebug) {
294 src = 'rethrow = rethrow || ' + rethrow.toString() + ';\n' + src;
299 fn = new Function(exports.localsName + ', escape, include, rethrow', src);
302 if (e instanceof SyntaxError) {
304 e.message += ' in ' + opts.filename;
306 e.message += ' while compiling ejs';
315 // Return a callable function which will execute the function
316 // created by the source-code, with the passed data as locals
317 return function (data) {
318 var include = function (path, includeData) {
319 var d = utils.shallowCopy({}, data);
321 d = utils.shallowCopy(d, includeData);
323 return includeFile(path, opts)(d);
325 return fn(data || {}, escape, include, rethrow);
330 this.generateSource = function () {
332 , matches = this.parseTemplateText()
333 , d = this.opts.delimiter;
335 if (matches && matches.length) {
336 matches.forEach(function (line, index) {
341 // If this is an opening tag, check for closing tags
342 // FIXME: May end up with some false positives here
343 // Better to store modes as k/v with '<' + delimiter as key
344 // Then this can simply check against the map
345 if ( line.indexOf('<' + d) === 0 // If it is a tag
346 && line.indexOf('<' + d + d) !== 0) { // and is not escaped
347 closing = matches[index + 2];
348 if (!(closing == d + '>' || closing == '-' + d + '>')) {
349 throw new Error('Could not find matching close tag for "' + line + '".');
352 // HACK: backward-compat `include` preprocessor directives
353 if ((include = line.match(/^\s*include\s+(\S+)/))) {
354 includeOpts = utils.shallowCopy({}, self.opts);
355 includeSrc = includeSource(include[1], includeOpts);
356 includeSrc = ';(function(){' + includeSrc + '})();';
357 self.source += includeSrc;
367 this.parseTemplateText = function () {
368 var str = this.templateText
370 , result = pat.exec(str)
376 firstPos = result.index;
377 lastPos = pat.lastIndex;
379 if (firstPos !== 0) {
380 arr.push(str.substring(0, firstPos));
381 str = str.slice(firstPos);
385 str = str.slice(result[0].length);
386 result = pat.exec(str);
396 this.scanLine = function (line) {
398 , d = this.opts.delimiter
401 function _addOutput() {
403 line = line.replace('\n', '');
406 // Preserve literal slashes
407 line = line.replace(/\\/g, '\\\\');
409 // Convert linebreaks
410 line = line.replace(/\n/g, '\\n');
411 line = line.replace(/\r/g, '\\r');
413 // Escape double-quotes
414 // - this will be the delimiter during execution
415 line = line.replace(/"/g, '\\"');
416 self.source += ';__output.push("' + line + '");';
419 newLineCount = (line.split('\n').length - 1);
423 this.mode = Template.modes.EVAL;
426 this.mode = Template.modes.ESCAPED;
429 this.mode = Template.modes.RAW;
432 this.mode = Template.modes.COMMENT;
435 this.mode = Template.modes.LITERAL;
436 this.source += ';__output.push("' + line.replace('<' + d + d, '<' + d) + '");';
440 if (this.mode == Template.modes.LITERAL) {
445 this.truncate = line.indexOf('-') === 0;
448 // In script mode, depends on type of tag
450 // If '//' is found without a line break, add a line break.
452 case Template.modes.EVAL:
453 case Template.modes.ESCAPED:
454 case Template.modes.RAW:
455 if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
460 // Just executing code
461 case Template.modes.EVAL:
462 this.source += ';' + line;
464 // Exec, esc, and output
465 case Template.modes.ESCAPED:
466 // Add the exec'd, escaped result to the output
467 // Have to prevent the string-coercion of `undefined` and `null`
468 // in the `escape` function -- making a `join` call like below unnecessary
469 this.source += ';__output.push(escape(' +
470 line.replace(_TRAILING_SEMCOL, '').trim() + '))';
473 case Template.modes.RAW:
474 // Add the exec'd result to the output
475 // Using `join` here prevents string-coercion of `undefined` and `null`
476 // without filtering out falsey values like zero
477 this.source += ';__output.push(' +
478 line.replace(_TRAILING_SEMCOL, '').trim() + ')';
480 case Template.modes.COMMENT:
483 // Literal <%% mode, append as raw output
484 case Template.modes.LITERAL:
489 // In string mode, just add the output
495 if (self.opts.compileDebug && newLineCount) {
496 this.currentLine += newLineCount;
497 this.source += ';__line = ' + this.currentLine + ';';
503 exports.__express = exports.renderFile;
505 // Add require support
506 /* istanbul ignore else */
507 if (require.extensions) {
508 require.extensions['.ejs'] = function (module, filename) {
509 filename = filename || /* istanbul ignore next */ module.filename;
514 , template = fs.readFileSync(filename).toString().trim()
515 , fn = compile(template, options);
516 module._compile('module.exports = ' + fn.toString() + ';', filename);
520 exports.VERSION = _VERSION_STRING;
522 /* istanbul ignore if */
523 if (typeof window != 'undefined') {
524 window.ejs = exports;