Skip to content

Commit

Permalink
Merge pull request jashkenas#505 from braddunbar/arbitrary-code
Browse files Browse the repository at this point in the history
Allow natural multi-line code evaluation in templates.
  • Loading branch information
jashkenas committed Mar 12, 2012
2 parents 34305bc + 414fafb commit 144dcb1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 8 deletions.
2 changes: 2 additions & 0 deletions test/test.html
Expand Up @@ -18,6 +18,7 @@
<body>
<div class="underscore-test">
<h1 id="qunit-header">Underscore Test Suite</h1>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
Expand All @@ -34,6 +35,7 @@ <h1 class="qunit-header">Underscore Speed Suite</h1>

<script type="text/html" id="template">
<%
// a comment
if (data) { data += 12345; }; %>
<li><%= data %></li>
</script>
Expand Down
10 changes: 9 additions & 1 deletion test/utility.js
@@ -1,6 +1,14 @@
$(document).ready(function() {

module("Utility");
var templateSettings = _.templateSettings;

module("Utility", {

teardown: function() {
_.templateSettings = templateSettings;
}

});

test("utility: noConflict", function() {
var underscore = _.noConflict();
Expand Down
22 changes: 15 additions & 7 deletions underscore.js
Expand Up @@ -905,7 +905,15 @@
// Within an interpolation, evaluation, or escaping, remove HTML escaping
// that had been previously added.
var unescape = function(code) {
return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
return code.replace(/\\(\\|'|r|n|t)/g, function(match, char) {
switch (char) {
case '\\': return '\\';
case "'": return "'";
case 'r': return '\r';
case 'n': return '\n';
case 't': return '\t';
}
});
};

// JavaScript micro-templating, similar to John Resig's implementation.
Expand All @@ -917,18 +925,18 @@
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
.replace(c.escape || noMatch, function(match, code) {
return "',_.escape(" + unescape(code) + "),'";
return "',_.escape(" + unescape(code) + "),\n'";
})
.replace(c.interpolate || noMatch, function(match, code) {
return "'," + unescape(code) + ",'";
return "'," + unescape(code) + ",\n'";
})
.replace(c.evaluate || noMatch, function(match, code) {
return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
return "');" + unescape(code) + ";\n__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', '_', tmpl);
if (data) return func(data, _);
Expand Down

0 comments on commit 144dcb1

Please sign in to comment.