views:

27

answers:

2

I'm developing under Pylons using Mako templates. The problem is that I need to assign a string from some attribute of tmpl_context to a JavaScript variable in a page body. The additional problem is that this string can be quite arbitrary, ie can contain such characters like ", ', <, >, etc... Is there a common way to do such assignment? I've tried something like:

<script>
    ...
    var a = "${c.my_string}";
    ...
</script>

but I get quotation marks and HTML special characters escaped. But I would not like to disable filtering because of possible danger of executing of unexpected code.

A: 

if I understood what you want, try webhelpers.html.literal:

helper:

from webhelpers.html import literal

html:

<script>
    document.write('${h.literal(c.my_string)}');
</script>

this is better than ${c.mystring|n} escaping html

renatopp
Not quite that. The aim is assign the value of c.my_string to a JS variable unchanged. For instance, if c.my_string is foo<>_"'"bar then I want some variable `a` to contain exactly foo<>_"'"bar.
eigenein
AFAIK literal() does not escape quotes nor does it filter html. So its same as |n - it tells escape() that its content is already escaped.
Daniel Kluev
+2  A: 

You have some arbitrary data in c.my_string, and therefore do not want to use "|n", right?

Quickiest way to escape it in JS-style escaping would be

var a = ${c.my_string.__repr__()|n}; # Note lack of "" around it! 

However I'm unsure about <> characters (with something like </script> inserted), maybe you would also want to use .replace('<', '&lt;');

For unicode you will need to also strip 'u' character from start of the string.

Daniel Kluev
Right, that seems to be exactly I need. I think the </script> problem is better to solve with .replace('<', '\u003c') because .replace('<', '<') changes the source string.
eigenein