本文介绍了如何编写多行Jinja语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Jinja模板中有一个if语句,出于可读性原因,我希望将其编写为多态.考虑一下情况

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.. %}

推荐答案

根据文档: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements ,只要代码周围有括号/括号,您就可以使用多行语句.示例:

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 %}

使用line_statement_prefix = '#' *代码看起来像这样:

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

*这是在 Environment :

*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='#'
)

或使用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 = '#'

这篇关于如何编写多行Jinja语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 06:27