当在jinja2模板中变量未定义时如何删除行

3

我有一个简单的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

有可能让这个变量贯穿整行吗?当变量未定义时消失?
1个回答

2
你可以在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 %}

1
虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。仅限代码的答案是不被鼓励的。 - Ajean
1
其实我一直在试图避免使用这种解决方案。我的模板变得有点复杂,这只会增加更多的混淆。 - Konrad Klimczak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接