From 81cb0d3a8617b47cbef86c500bad19bddecd7c46 Mon Sep 17 00:00:00 2001 From: Stuart Knightley Date: Thu, 8 Dec 2011 11:33:31 -0800 Subject: [PATCH 1/2] Add failing test for Javascript in templates Uses an escaped character in Javascript embedded in a template. Gets incorrectly replaced when templating. --- test/utility.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/utility.js b/test/utility.js index e49d5e27f..c609dc2c3 100644 --- a/test/utility.js +++ b/test/utility.js @@ -63,6 +63,10 @@ $(document).ready(function() { result = fancyTemplate({people : {moe : "Moe", larry : "Larry", curly : "Curly"}}); equals(result, "", 'can run arbitrary javascript in templates'); + var escapedCharsInJavascriptTemplate = _.template(""); + result = escapedCharsInJavascriptTemplate({numbers: "one\ntwo\nthree\nfour"}); + equals(result, "", 'Can use escaped characters (e.g. \\n) in Javascript') + var namespaceCollisionTemplate = _.template("<%= pageCount %> <%= thumbnails[pageCount] %> <% _.each(thumbnails, function(p) { %>
\">
<% }); %>"); result = namespaceCollisionTemplate({ pageCount: 3, From c8ecb47765b06c8ba39176f77162c4180352d33d Mon Sep 17 00:00:00 2001 From: Stuart Knightley Date: Thu, 8 Dec 2011 11:36:20 -0800 Subject: [PATCH 2/2] Templating fix for when an escaped character is used in Javascript If an escaped character (e.g. \n) is used in embedded Javascript inside a template then it gets escaped to \\n. If someone has put an escaped character in their JS then they probably want it left that way. This commit replaces \\s with a single \ when inside evaluation tags, reverting the previous template escaping. --- underscore.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/underscore.js b/underscore.js index b6b28137d..cd2d2bb0a 100644 --- a/underscore.js +++ b/underscore.js @@ -909,7 +909,8 @@ }) .replace(c.evaluate || null, function(match, code) { return "');" + code.replace(/\\'/g, "'") - .replace(/[\r\n\t]/g, ' ') + ";__p.push('"; + .replace(/[\r\n\t]/g, ' ') + .replace(/\\\\/g, '\\') + ";__p.push('"; }) .replace(/\r/g, '\\r') .replace(/\n/g, '\\n')