Python jinja2模板中未定义变量时如何删除行
我有一个简单的jinja2模板:Python jinja2模板中未定义变量时如何删除行,python,templates,jinja2,Python,Templates,Jinja2,我有一个简单的jinja2模板: {% for test in tests %} {{test.status}} {{test.description}}: {{test.message}} Details: {% for detail in test.details %} {{detail}} {% endfor %} {% endfor %} 当“test”对象的所有变量定义如下时,哪一个工作得非常好: from 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
但有时“test”对象可能没有“message”属性,在这种情况下,有一行空行:
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 %}
虽然此代码可能会回答该问题,但提供有关此代码为什么和/或如何回答该问题的附加上下文可提高其长期价值。不鼓励只使用代码的答案。实际上我正试图避免这种解决方案。我的模板有点复杂,它增加了更多的混乱。