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.. %}
Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.
Jinja2 allows us to manually control generation of whitespaces. You do it by using a minus sing - to strip whitespaces from blocks, comments or variable expressions. You need to add it to the start or end of given expression to remove whitespaces before or after the block, respectively.
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 = '#'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With