76

I have an if statement in my Jinja templates which I want to write it in multines for readability reasons. Consider the case

{% if (foo == 'foo' or bar == 'bar') and (fooo == 'fooo' or baar == 'baar') etc.. %}
topless
  • 8,069
  • 11
  • 57
  • 86

1 Answers1

123

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • 1
    Have you tried this? Pretty sure you'd get: `expected token 'end of statement block', got 'pass'` when running this. Similarly when replacing `pass` by a `set` or regular assignment, I think you'll get `expected token 'end of statement...`. Instead you'll have to wrap each statement in `{% %}` separately, e.g.: `{% if ... %} {% set x = 1 %} {% endif %}`. – Tim Diels Feb 02 '19 at 15:16
  • I suppose you meant to place the `%}` above `pass`, as you did with the `#` syntax. – Tim Diels Feb 02 '19 at 15:17
  • @timdiels: a belated thank you for the comments. I corrected the examples and updated the links. – mechanical_meat Jan 03 '20 at 20:38