问题
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