header_pic
Back to blog home

How to Write a Multiline Jinja Statement

by Adam on 2017-07-01

Originally posted here: https://stackoverflow.com/a/15168895/42346

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 parentheses, braces, or brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    {{ test }}
{% endif %}

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

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    {{ test }}
# 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 = '#'



tags: python jinja jinja2 multiline template

Post thanked 0 time(s).

Related posts: