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. B开发者_如何学Cut I would not like to disable filtering because of possible danger of executing of unexpected code.
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('<', '<');
For unicode you will need to also strip 'u' character from start of the string.
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
精彩评论