3

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.

eigenein
  • 2,083
  • 3
  • 25
  • 43

2 Answers2

2

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
  • 11,025
  • 2
  • 36
  • 36
  • Right, that seems to be exactly I need. I think the problem is better to solve with .replace('<', '\u003c') because .replace('<', '<') changes the source string. – eigenein Aug 01 '10 at 15:54
1

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
  • 1,275
  • 10
  • 17
  • 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 Aug 01 '10 at 15:34
  • 2
    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 Aug 01 '10 at 15:34