Scott Colby
Scott Colby

Reputation: 1430

Jinja Trimming Whitespace Around Single-Line If Statement

I would like to create a Jinja template along these lines:

Some list:
    - foo
    {% if a %}- bar: a{% endif %}
    {% if b %}- baz: b{% endif %}
    - quux

That renders like the "Rendering Goals" below.

However, I can't find a combination of - and + modifiers that does what I want in all cases without resorting to putting the {% if ... %} and {% endif %} tags on separate lines.

Specifically, I don't want any blank lines or extra whitespace when a and/or b are False.

The best I can do is this:

Some list:
    - foo
    {%- if a %}
    - bar: a
    {%- endif %}
    {%- if b %}
    - baz: b
    {%- endif %}
    - quux

Is it possible to create a more compact template than that?

Rendering Goals:

Some list:
    - foo
    - bar: a
    - baz: b
    - quux
Some list:
    - foo
    - bar: a
    - quux
Some list:
    - foo
    - baz: b
    - quux
Some list:
    - foo
    - quux

Upvotes: 2

Views: 437

Answers (1)

hrtednrup
hrtednrup

Reputation: 133

I know this is old, but I'd been struggling with this recently. I can't say this is a solution but more of a workaround. The jinja template where the conditional lines are contained within control blocks on separate lines may be better.

This template:

Some list:
    - foo
{% if a %}{{'    - bar: a\n'}}{% endif %}
{% if b %}{{'    - baz: b\n'}}{% endif %}
    - quux

with the trim_blocks parameter set to True will render as your stated goal.

Upvotes: 1

Related Questions