How to get some string values ​​from a Pylons controller that will be assigned to JavaScript variables using Mako?

I am developing for Pylons using Mako templates. The problem is that I need to assign a string from some tmpl_context attribute to a JavaScript variable in the body of the page. An additional problem is that this line can be quite arbitrary, i.e. May contain characters such as ",", <,>, etc. Is there a general way to accomplish this? I tried something like:

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

but I get quotes and special HTML characters. But I would not want to turn off filtering because of the possible danger of running unexpected code.

+3
source share
2 answers

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

The fastest way to avoid this in JS-style shielding would be

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

However, I'm not sure about the characters <>(with the addition of something like </script>), you might also want to use.replace('<', '&lt;');

For Unicode, you also need to remove the "u" character from the beginning of the line.

+2
source

If I understand what you want, try webhelpers.html.literal:

helpers:

from webhelpers.html import literal

HTML:

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

it's better than ${c.mystring|n}html escaping

+1
source

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


All Articles