Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a multiline Jinja statement

Tags:

jinja2

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.. %} 
like image 793
topless Avatar asked Mar 01 '13 23:03

topless


People also ask

What is the difference between Jinja and Jinja2?

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.

How do you get rid of whitespace in Jinja?

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.


1 Answers

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 = '#' 
like image 104
mechanical_meat Avatar answered Oct 02 '22 14:10

mechanical_meat