开发者

How do I get some string values from Pylons controller be assigned to JavaScript variables with Mako?

开发者 https://www.devze.com 2023-01-09 14:20 出处:网络
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

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('<', '&lt;');

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

0

精彩评论

暂无评论...
验证码 换一张
取 消