coredumperror
coredumperror

Reputation: 9151

Is there a way to strip whitespace around a template tag?

I have a template for a plaintext email:

Here's some info.

{% if variable %}
Additional info.
{% else %}
Alternative info.
{% endif %}

{% if another_variable %}
IMPORTANT MESSAGE
{% endif %}

Final thoughts.

Unfortunately, since this is a plaintext template, rather than HTML, the newline characters that appear after each template tag are being included in the output. So if variable == True and another_variable == False, the output looks like this:

Here's some info.


Additional info.



Final thoughts.

There are a ton of extra empty lines between everything, which I would like for there to be just one.

Is there any way around this problem without mushing all the tags together (which makes the template difficult to read)?

Upvotes: 1

Views: 883

Answers (2)

Domen Blenkuš
Domen Blenkuš

Reputation: 2242

Try this:

import re
regex = re.compile(r'\n+')
regex.sub('\n', template)

This will replace consecutive newlines with single one.

Upvotes: 1

shellbye
shellbye

Reputation: 4858

You can custom your one. See here for some guidance.

Upvotes: 0

Related Questions