Escape Single Quotes in a Template Set

Do you avoid single quotes in the template set for the necessary javascript handlers? If so, how do you do it.

[% SET s = "A'B'C" %] <a href="/abc.html" onclick="popup('[% s | html_entity %]')">ABC</a> 

html_entity clearly not working because it is processing a double quote. So how do you do this?

+4
source share
5 answers

I do not use the built-in event handlers - for the same reason, I refuse to use the style attribute for css. JQuery simply simplifies the implementation of class="foo" on html and $('.foo').click( function () {} ) in an external .js file.

But in order to do everything possible to answer this question, look at these documents on Template::Filter for those that are in the kernel.

It seems you could do [% s | replace( "'", "\'" ) %] [% s | replace( "'", "\'" ) %] to avoid single quotes. Or you can probably write a more complex javascript sanitizer parser that only allows function calls and create your own Template :: Filter

+8
source

2018 update for reference:

TT has a method for this called squote for highlighting single quotes and dquote for double quotes.

 [% tim = "Tim O'Reilly" %] [% tim.squote %] # Tim O\'Reilly 

The requested link will look something like this:

 <a href="/abc.html" onclick="popup('[% s.squote %]')">ABC</a> 

http://www.template-toolkit.org/docs/manual/VMethods.html#section_squote

+2
source

You can try: popup('[% s | html %]') .

+1
source

Perl is not the strongest language ... But!

The easiest way I've found is to use the JSON module. In a module called JS.pm or something:

 use JSON; sub encode () { my $self = shift; my $string = shift; $json = JSON->new->allow_nonref; return $json->encode( $string ); } 

More details here: http://search.cpan.org/~makamaka/JSON-2.90/lib/JSON.pm

Then in your template:

 [% use JS; %] <script> var escaped_string = [% JS.encode( some_template_variable ) %]; </script> 
+1
source

Remember to double escape with a slash in the replacement, otherwise it will be interpreted as an acceleration of the apostrophe.

 [% string.replace( "'", "\\'" ) %] 
0
source

Source: https://habr.com/ru/post/1312092/


All Articles