Search code examples
pythonjinja2templating

conditionally apply jinja2 filter


I'd like to conditionally apply a filter to a section of text. For example:

{% filter upper %}
    some text
{% endfilter %}

changes to something like:

{% filter upper if X == 1 %}
    some text
{% endfilter %}

Perhaps that is not possible, and the solution is an if/else statement. Then "some text" will get repeated twice, once for the "if" and once for the "else". That's fine in a small example. But what if the text is very long and contains variables? So, the next choice to move "some text" into a macro. Again, if the text contains many variables, you have to set up all the arguments to the macro, it becomes more complicated. Maybe those are the only choices though. Is there a way to succinctly combine a conditional and a filter?


Solution

  • You can move the logic in the filter with a custom one :

    Filter definition :

    def custom_upper(text, X):
      if X == 1:
        return text.upper()
      return text
    
    environment.filters['custom_upper'] = custom_upper
    

    Template :

    {% filter custom_upper(X) %}
      some text
    {% endfilter %}
    

    https://jinja.palletsprojects.com/en/2.11.x/api/#writing-filters