[Catalyst] I18N with quotation marks

Ton Voon ton.voon at opsera.com
Thu Jul 2 08:35:05 GMT 2009

On 1 Jul 2009, at 18:22, Ton Voon wrote:

> I am localising our app, which consists of strings in html and in  
> dynamic javascript snippets. However, if the translated value  
> contains quotations (such as: s'il vous plait), then it could break  
> the HTML:
> <select value='[% c.loc("Please select one") %]'>
> or the javascript:
> alert('[% c.loc("Please select one") %]');
> We also sometimes use double quotes for attributes instead of single  
> quotes.
> What is the best practise? Always run c.loc() through a filter to  
> convert to HTML entities? (Although in FF3.0 alert('Impossible  
> d&#39;exécuter snmpget pour tester la connexion'); does not give the  
> single quote).
> I was considering creating methods of c.hloc() (for a html  
> environment) and c.jloc() (for a javascript environment), but then  
> the xgettext.pl helper does not look for these method names.


Thanks for all the responses.

I think I now realise it depends on the context of the output so,  
given that the translated string is "as-is" (without any markup or  
html elements), then some filtering is required based on where the  
translated value belongs.

This is my current thinking:

For HTML text, you should pass through the html filter, eg:

<p>[% c.loc("Some text that might have < or > in it") | html %]</p>

For HTML elements, you should use double quotes for quoting attributes  
and then pass the string through the html filter, eg,

<select value="[% c.loc("May have some single or double quotes in") |  
html %]">

For javascript in <script> blocks, you should use single quotes for  
the string value and pass through an escape_js filter, eg:

var string = '[% c.loc("May have single quotes or \ in it") |  
escape_js %]';

For javascript in HTML elements, you should use double quotes for  
quoting the attributes and single quotes for the javascript strings  
and pass through the escape_js filter and the html filter, eg:

<select onclick=" alert('[% c.loc("May have all sorts of things in  
it") | escape_js | html %]') ">

The escape_js filter is defined as (From Larry Leszcznski's example):

$Template::Stash::SCALAR_OPS->{escape_js} = sub {
    my $s = shift;
    $s =~ s/\\/\\\\/g;
    $s =~ s/'/\\'/g;
    return $s;

Does everyone agree this makes sense? If so, any objections if I add  
this to http://dev.catalystframework.org/wiki/best_practices?


More information about the Catalyst mailing list