Skip to content

Commit

Permalink
Merge pull request tj#45 from whoatemydomain/master
Browse files Browse the repository at this point in the history
Slurp( -%>) Modification
  • Loading branch information
tj committed Mar 25, 2012
2 parents eb66597 + 7a57daa commit 64e3436
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 3 deletions.
1 change: 1 addition & 0 deletions Readme.md
Expand Up @@ -17,6 +17,7 @@ Embedded JavaScript templates.
* Supports tag customization
* Filter support for designer-friendly templates
* Client-side support
* Newline slurping with `<% code -%>` or `<% -%>` or `<%= code -%>` or `<%- code -%>`

## Example

Expand Down
16 changes: 13 additions & 3 deletions lib/ejs.js
Expand Up @@ -118,6 +118,7 @@ var parse = exports.parse = function(str, options){

var lineno = 1;

var slurp = false;
for (var i = 0, len = str.length; i < len; ++i) {
if (str.slice(i, open.length + i) == open) {
i += open.length
Expand All @@ -143,7 +144,12 @@ var parse = exports.parse = function(str, options){
, js = str.substring(i, end)
, start = i
, n = 0;


if(js[js.length-1]=='-'){
js = js.substring(0,js.length-2);
slurp = true;
}

while (~(n = js.indexOf("\n", n))) n++, lineno++;
if (js.substr(0, 1) == ':') js = filtered(js);
buf.push(prefix, js, postfix);
Expand All @@ -156,8 +162,12 @@ var parse = exports.parse = function(str, options){
} else if (str.substr(i, 1) == "\r") {
buf.push(" ");
} else if (str.substr(i, 1) == "\n") {
buf.push("\\n");
lineno++;
if(slurp) {
slurp = false;
} else {
buf.push("\\n");
lineno++;
}
} else {
buf.push(str.substr(i, 1));
}
Expand Down
39 changes: 39 additions & 0 deletions test/ejs.test.js
Expand Up @@ -286,5 +286,44 @@ module.exports = {
var lineno = parseInt(err.toString().match(/ejs:(\d+)\n/)[1]);
assert.deepEqual(lineno, 6, "Error should been thrown on line 3, was thrown on line "+lineno);
}
},

'test slurp' : function() {
var expected = 'me\nhere',
str = 'me<% %>\nhere';
assert.equal(expected, ejs.render(str));

var expected = 'mehere',
str = 'me<% -%>\nhere';
assert.equal(expected, ejs.render(str));

var expected = 'me\nhere',
str = 'me<% -%>\n\nhere';
assert.equal(expected, ejs.render(str));

var expected = 'me inbetween \nhere',
str = 'me <%= x %> \nhere';
assert.equal(expected, ejs.render(str,{x:'inbetween'}));

var expected = 'me inbetween here',
str = 'me <%= x -%> \nhere';
assert.equal(expected, ejs.render(str,{x:'inbetween'}));

var expected = 'me <p>inbetween</p> here',
str = 'me <%- x -%> \nhere';
assert.equal(expected, ejs.render(str,{x:'<p>inbetween</p>'}));

var expected = '\n Hallo 0\n\n Hallo 1\n\n',
str = '<% for(var i in [1,2]) { %>\n' +
' Hallo <%= i %>\n' +
'<% } %>\n';
assert.equal(expected, ejs.render(str));

var expected = ' Hallo 0\n Hallo 1\n',
str = '<% for(var i in [1,2]) { -%>\n' +
' Hallo <%= i %>\n' +
'<% } -%>\n';
assert.equal(expected, ejs.render(str));
}

};

0 comments on commit 64e3436

Please sign in to comment.