3

I have a simple jinja2 template:

{% for test in tests %}
{{test.status}} {{test.description}}:
    {{test.message}}
    Details:
        {% for detail in test.details %}
        {{detail}}
        {% endfor %}
{% endfor %}

Which work really good when all of variable of 'test' object are defined like here:

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'])

Then output looks like this:

ERROR Description of test:
    Some test message what went wrong and something
    Details:
        First error
        Second error

But sometimes it is possible that 'test' object will not have 'message' property and in this case there is an empty line:

ERROR Description of test:

    Details:
        First error
        Second error

Is it possible to make this variable stick to whole line? to make it disappear when variable is undefined?

Konrad Klimczak
  • 1,474
  • 2
  • 22
  • 44

1 Answers1

2

You can put a if condition inside the for loop to avoid blank line if there is no message.

{% for test in tests %}
{{test.status}} {{test.description}}:
    {% if test.message %}
        {{test.message}}
    {% endif %}
    Details:
        {% for detail in test.details %}
        {{detail}}
        {% endfor %}
{% endfor %}
SumanKalyan
  • 1,681
  • 14
  • 24
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. Code-only answers are discouraged. – Ajean Aug 29 '16 at 23:14
  • 1
    Actually I was trying to avoid this solution. My template got a little complex and it's adding even more confusion. – Konrad Klimczak Aug 30 '16 at 13:30