Search code examples
pythondjangomako

How do I display ${'None'} in a Django Mako template?


I am trying to show words from a list of possible values (including 'None', 'Little', and 'More') on a Django website using Mako-templates. Only two of the three words are actually rendered. 'None' gets interpreted as None and is converted to an empty string when I call ${variable}.

In troubleshooting, I determined that actually writing ${'None'} in the mako template returns an empty string to the browser.

Is there a way to get the mako template to print this string?

Thanks!


Solution

  • Mako has a filter system which uses | operator to apply escape filters to ${}.

    Without any configuration Mako by default would use unicode filter implicitly. Though you can always change the default filter Mako uses by setting the default_filters argument.

    The n filter disable all default filtering; only filters specified in the local expression tag will be applied.

    So by default, Mako should render ${"None"} as None instead of empty string. The fact that it only works for you when adding n filter suggests that you have probably set default_filters to some other filter that escaped string None into empty string. n will fix it, but before you use it you should probably dig a bit further to see if default_filters has been set somewhere in your code.

    WARNING: n filter shouldn't be applied normally for any user (the user of your websites that is) input, because no-escaping means you are vulnerable to a range of attacks such as the XSS.