Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mako escaping issue within Pyramid

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)
like image 359
drnextgis Avatar asked Aug 27 '12 06:08

drnextgis


2 Answers

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"
like image 79
Martijn Pieters Avatar answered Nov 08 '22 05:11

Martijn Pieters


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...

like image 43
yentsun Avatar answered Nov 08 '22 04:11

yentsun