Subject: | Enhancement Request - JSON escaping mechanism |
We would like to use tmpl_vars in some of our JSON objects that are in
our HTML Templates. Unfortunately, at the moment we have to escape the
variables before registering them with the template as the js escape
option will escape an apostrophe but most JSON parsers will complain
about escaped apostrophes. http://json.org/
e.g. we would like to do:
var test = { "a" : "<tmpl_var escape='ijson' name='myvar'>" };
I'm using "ijson" opposed to json given our variable is inside quotes
and we would rather not have external quotes.
I've attached a patch which basically adds a new escape method called
ijson (js escape without escaping the apostrophe).
Not sure how you feel about this. It's a bit of a hack. I'm happy to
maintain something like this at my side if it gets rejected.
Thanks!
Subject: | patch.txt |
--- Compiler.pm.orig Wed Apr 27 12:10:27 2011
+++ Compiler.pm Thu Sep 1 15:45:31 2011
@@ -117,6 +117,11 @@
_expr_function( 'HTML::Template::Compiled::Utils::escape_js',
$exp, );
}
+ elsif ( $_ eq 'IJSON' ) {
+ $exp =
+ _expr_function( 'HTML::Template::Compiled::Utils::escape_ijson',
+ $exp, );
+ }
elsif ( $_ eq 'DUMP' ) {
$exp = _expr_method( 'dump', _expr_literal('$t'), $exp, );
}
--- Utils.pm.orig Wed Apr 27 12:10:27 2011
+++ Utils.pm Thu Sep 1 15:41:24 2011
@@ -11,14 +11,14 @@
@EXPORT_OK = (
@paths, qw(
&log &stack
- &escape_html &escape_html_all &escape_uri &escape_js
+ &escape_html &escape_html_all &escape_uri &escape_js &escape_ijson
&md5
)
);
%EXPORT_TAGS = (
walkpath => \@paths,
log => [qw(&log &stack)],
- escape => [qw(&escape_html &escape_uri &escape_js)],
+ escape => [qw(&escape_html &escape_uri &escape_js &escape_ijson)],
);
# These should be better documented
@@ -195,7 +195,24 @@
sub escape_js {
my ($var) = @_;
return $var unless defined $var;
- $var =~ s/(["'])/\\$1/g;
+ $var =~ s/([\\"'])/\\$1/g;
+ $var =~ s/\r/\\r/g;
+ $var =~ s/\n/\\n/g;
+ return $var;
+}
+
+=head2 escape_ijson
+
+ my $escaped_ijson = escape_ijson($raw_json);
+
+JavaScript-escapes the input string except for the apostrophe and returns it, so it can be used within a JSON element;
+
+=cut
+
+sub escape_ijson {
+ my ($var) = @_;
+ return $var unless defined $var;
+ $var =~ s/([\\"])/\\$1/g;
$var =~ s/\r/\\r/g;
$var =~ s/\n/\\n/g;
return $var;