我有一个简单的jinja2模板:
{% for test in tests %}
{{test.status}} {{test.description}}:
{{test.message}}
Details:
{% for detail in test.details %}
{{detail}}
{% endfor %}
{% endfor %}
当像下面这样定义“ test”对象的所有变量时,哪个工作真的很好:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('my_package', 'templates'), trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True)
template = env.get_template('template.hbs')
test_results = {
'tests': [
{
'status': 'ERROR',
'description': 'Description of test',
'message': 'Some test message what went wrong and something',
'details': [
'First error',
'Second error'
]
}
]
}
output = template.render(title=test_results['title'], tests=test_results['tests'])
然后输出如下所示:
ERROR Description of test:
Some test message what went wrong and something
Details:
First error
Second error
但是有时候“测试”对象可能没有“消息”属性,在这种情况下,空行是可能的:
ERROR Description of test:
Details:
First error
Second error
是否有可能使该变量坚持整行?使它在变量未定义时消失?
最佳答案
您可以在for循环中放置一个if条件,以避免在没有消息的情况下出现空行。
{% for test in tests %}
{{test.status}} {{test.description}}:
{% if test.message %}
{{test.message}}
{% endif %}
Details:
{% for detail in test.details %}
{{detail}}
{% endfor %}
{% endfor %}
关于python - jinja2模板中 undefined variable 时如何删除行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38595674/