Search code examples
pythonescapingpyramidmako

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)

Solution

  • 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"