Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for variable includes #197

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions lib/ejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,27 @@ function rethrow(err, str, filename, lineno){
throw err;
}

/**
* parse an object notation string to object entities to retrieve value
* Example:
* var options = { group : [{ name: "The Marx Brothers", members : [{name: "Chico"}, {name : "Harpo"} , {name : "Groucho"}, {name : "Zeppo"}] }] }
* parseObjectNotationString('group[0].members[2]["name"]', options)
* Output:
* Groucho
*
* @param {String} str
* @param {Object} context
* @api private
*/
function parseObjectNotationString(str, context){
var parts = str.match(/\w+/g), i, ref = context, undef;
for (i=0; i<parts.length; i++){
if (typeof ref[parts[i]] == 'undefined') return undef;
ref = ref[parts[i]];
}
return ref;
}

/**
* Parse the given `str` of ejs, returning the function body.
*
Expand Down Expand Up @@ -158,16 +179,24 @@ var parse = exports.parse = function(str, options){

if (0 == js.trim().indexOf('include')) {
var name = js.trim().slice(7).trim();
var value = parseObjectNotationString(name, options);
if (typeof value != 'undefined') name = value;
if (!filename) throw new Error('filename option is required for includes');
var path = resolveInclude(name, filename);
include = read(path, 'utf8');
include = exports.parse(include, { filename: path, _with: false, open: open, close: close, compileDebug: compileDebug });
var newOptions = { filename: path, _with: false, open: open, close: close, compileDebug: compileDebug };
var hop = Object.prototype.hasOwnProperty;
for (var key in options){
if (hop.call(options, key) && !hop.call(newOptions, key))
newOptions[key] = options[key];
}
include = exports.parse(include, newOptions);
buf += "' + (function(){" + include + "})() + '";
js = '';
}

while (~(n = js.indexOf("\n", n))) n++, lineno++;

switch(js.substr(0, 1)) {
case ':':
js = filtered(js);
Expand All @@ -179,7 +208,7 @@ var parse = exports.parse = function(str, options){
js = "";
break;
}

if (js) {
if (js.lastIndexOf('//') > js.lastIndexOf('\n')) js += '\n';
buf += prefix;
Expand Down