Commits

Anonymous committed 8f3822a

New "escapejs" filter (Django standard)

Comments (0)

Files changed (3)

demo/out/test_filters.html

        center       
 </pre>
 
+Escape JS: \" \'
+
 First letter: f
 
 Fix ampersands: &amp;

demo/templates/test_filters.html

 {{ "center"|center:20 }}
 </pre>
 
+Escape JS: {{ "\" '"|escapejs }}
+
 First letter: {{ "first"|first }}
 
 Fix ampersands: {{ "&"|fix_ampersands }}

src/erlydtl/erlydtl_filters.erl

 center(Input, Number) ->
     string:centre(lists:flatten(Input), Number).
 
+escapejs([Input]) when is_list(Input) ->
+    escapejs(Input);
+escapejs(Input) ->
+    escapejs(Input, []).
+
 first([[First|_Rest]]) ->
     [First].
 
 fix_ampersands(Input) ->
     fix_ampersands(lists:flatten(Input), []).
 
+force_escape([Input]) when is_list(Input) ->
+    force_escape(Input);
 force_escape(Input) when is_list(Input) ->
-    escape(lists:flatten(Input), []);
+    escape(Input, []);
 force_escape(Input) when is_binary(Input) ->
     escape(binary_to_list(Input), []);
 force_escape(Input) ->
 escape([C | Rest], Acc) ->
     escape(Rest, [C | Acc]).
 
+escapejs([], Acc) ->
+    lists:reverse(Acc);
+escapejs("'" ++ Rest, Acc) ->
+    escapejs(Rest, lists:reverse("\\'", Acc));
+escapejs("\"" ++ Rest, Acc) ->
+    escapejs(Rest, lists:reverse("\\\"", Acc));
+escapejs([C | Rest], Acc) ->
+    escapejs(Rest, [C | Acc]).
+
 fix_ampersands([], Acc) ->
     lists:reverse(Acc);
 fix_ampersands("&" ++ Rest, Acc) ->