Jinja2 exits filter operator ("|")

In jinja2, the operator is |

used as filtering eg {{ user_input | safe }}

. However, |

it is also a valid python operator, such as bitwise, or sets union, etc. Suppose I have the following code in my template

{% for elem in (set1 | set2) %} elem.render_some_string() {% endfor %}

      

Jinja throws an exception

File "some_template_file.txt", line xxx, in template
    {% for elem in (set1 | set2) %} elem.render_some_string() {% endfor %}
jinja2.exceptions.TemplateAssertionError: no filter named 'set2'

      

which is understandable. But is there a way to get around this, say ginny, so as not to interpret the operator |

as a filter? I hope the solution is better than "replace (set1 | set2)

with set1.union(set2)

" --- unless it is the only possible solution (or just the recommended solution).

+3


source to share


1 answer


You cannot use expressions |

in Jinja2 expressions to control anything other than a Jinja2 filter operation. Every statement using {%%}

or {{}}

(and so on) is not actually python. This is Jinja langage, lexed, dealt with Jinja and executed. Every piece of code you put in is not "sketched" as you might, although even the tag is +

parsed and executed in the Jinja2 parser module ( GitHub-Jinja2 / parser.py # L450 ). So |

is a Jinja grammar symbol and cannot be changed to its python meaning.

The reason you can name your methods is because your objects are still real and they retain all their capabilities. The solution you suggest to use .union

is the only available solution that you have.



FYI: There is no open (or closed) issue in Jinja2 to allow such a possibility (and it might get rejected if it were in my opinion)

+1


source







All Articles