Blob Blame History Raw
From c524200b961e70c292bf42848515c4c4d8cf162a Mon Sep 17 00:00:00 2001
From: Dan Callaghan <dcallagh@redhat.com>
Date: Tue, 24 Dec 2013 11:16:01 +1000
Subject: [PATCH 01/14] escape JS string literals correctly in JST filter

(cherry picked from commit fad3aded6837751f68b6f3af6851ef19c64dd04c)

diff --git a/src/webassets/filter/jst.py b/src/webassets/filter/jst.py
index 7f1ff1f..19822cf 100644
--- a/src/webassets/filter/jst.py
+++ b/src/webassets/filter/jst.py
@@ -1,4 +1,8 @@
 import os
+try:
+    import json
+except ImportError:
+    import simplejson as json
 from webassets.filter import Filter
 from webassets.utils import common_path_prefix
 
@@ -148,14 +152,14 @@ class JST(JSTemplateFilter):
             out.write("%s\n" % _jst_script)
 
         for name, hunk in self.iter_templates_with_base(hunks):
-            # Make it a valid Javascript string. Is this smart enough?
-            contents = hunk.data().replace('\n', '\\n').replace("'", r"\'")
+            # Make it a valid Javascript string.
+            contents = json.dumps(hunk.data())
 
             out.write("%s['%s'] = " % (namespace, name))
             if self.template_function is False:
-                out.write("'%s';\n" % (contents))
+                out.write("%s;\n" % (contents))
             else:
-                out.write("%s('%s');\n" % (
+                out.write("%s(%s);\n" % (
                     self.template_function or 'template', contents))
 
         if self.bare is False:
diff --git a/tests/test_filters.py b/tests/test_filters.py
index 62f4e7c..6fa3023 100644
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -1008,7 +1008,7 @@ class TestJST(TempEnvironmentHelper):
         """Output strings directly if template_function == False."""
         self.env.config['JST_COMPILER'] = False
         self.mkbundle('templates/*.jst', filters='jst', output='out.js').build()
-        assert "JST['foo'] = '" in self.get('out.js')
+        assert "JST['foo'] = \"" in self.get('out.js')
 
     def test_namespace_config(self):
         self.env.config['JST_NAMESPACE'] = 'window.Templates'
@@ -1074,6 +1074,13 @@ class TestJST(TempEnvironmentHelper):
 
         assert 'new value' in self.get('out.js')
 
+    def test_backslashes_escaped(self):
+        """Test that JavaScript string literals are correctly escaped.
+        """
+        self.create_files({'backslashes.jst': """<input type="text" pattern="\S*"/>"""})
+        self.mkbundle('*.jst', filters='jst', output='out.js').build()
+        assert r"""template("<input type=\"text\" pattern=\"\\S*\"/>")""" in self.get('out.js')
+
 
 class TestHandlebars(TempEnvironmentHelper):
 
-- 
1.9.3