Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

python - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...