Skip to main content
 首页 » 编程设计

python之jinja2模板中 undefined variable 时如何删除行

2024年10月17日13cloudgamer

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