Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions doc/build/filtering.rst
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,20 @@ will render ``myexpression`` with no filtering of any kind, and:

will render ``myexpression`` using the ``trim`` filter only.

Including the ``n`` filter in a ``<%page>`` tag will only disable
``default_filters``. In effect this makes the filters from the tag replace
default filters instead of adding to them. For example:

.. sourcecode:: mako

<%page expression_filter="n, json.dumps"/>
data = {a: ${123}, b: ${"123"}};

will suppress turning the values into strings using the default filter, so that
``json.dumps`` (which requires ``imports=["import json"]`` or something
equivalent) can take the value type into account, formatting numbers as numeric
literals and strings as string literals.

Filtering Defs and Blocks
=========================

Expand Down
2 changes: 1 addition & 1 deletion mako/codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -802,7 +802,7 @@ def locate_encode(name):
if is_expression:
if self.compiler.pagetag:
args = self.compiler.pagetag.filter_args.args + args
if self.compiler.default_filters:
if self.compiler.default_filters and "n" not in args:
args = self.compiler.default_filters + args
for e in args:
# if filter given as a function, get just the identifier portion
Expand Down
11 changes: 11 additions & 0 deletions test/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,17 @@ def test_nflag(self):
)
assert t.render().strip() == "&lt;tag&gt;this is html&lt;/tag&gt;"

def test_global_json(self):
t = Template(
"""
<%!
import json
%><%page expression_filter="n, json.dumps"/>
data = {a: ${123}, b: ${"123"}};
"""
)
assert t.render().strip() == """data = {a: 123, b: "123"};"""

def test_non_expression(self):
t = Template(
"""
Expand Down