Mako escaping issue within Pyramid

点点圈 提交于 2019-12-23 09:38:14

问题


I need to put javascript function to mako template. The first argument of this function is string, so I write in my *.mako file (dict(field_name='geom')):

init_map(
    '${field_name}'
);

But when I see my html page it loks like:

init_map(
    'geom'
)

How I can disable escaping in this case?

Rendering performs the following way:

from pyramid.renderers import render
render('georenderer/map.mako', template_args)

回答1:


You'll need to include the quotes in your expression I think. You can use the json module to output valid JavaScript literals:

dict(field_name=json.dumps('geom'))

and in your template:

init_map(
    ${field_name | n}
);

The quotes are then generated by the .dumps() function, and the | n filter ensures they are not escaped; you've already made your values JavaScript safe, you don't need them HTML-safe either.

The added advantage is that the module will escape any quotes in your JavaScript values as well, and handle unicode properly:

>>> import json
>>> print json.dumps(u'Quotes and unicode: " \u00d8')
"Quotes and unicode: \" \u00d8"



回答2:


Try n filter. According to the docs, it disables escaping (or any other default filtering):

${field_name | n}

UPDATE: Sorry I didn't notice that the quotes are around the expression. And now it seem very strange...



来源:https://stackoverflow.com/questions/12137421/mako-escaping-issue-within-pyramid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!