Introduction
The Django template filters: linebreaks
and linebreaksbr
both handle the conversion of line breaks to plain text. Although they behave differently in terms of how the HTML is generated.
1. linebreaks
:
- Converts the plain text string into a HTML paragraph
<p>
when there are no newline characters (\n
) found in the plain text. - Converts the newline character (
\n
) in a plain text string into HTML<p>
(paragraph) and<br>
(line break) tags. - Each block of text separated by two or more newlines becomes a
<p>
tag, and single newlines within that block are converted to<br>
tags.
Example:
{% with text="This is line one.\nThis is line two.\n\nThis is a new paragraph." %}
{{ text|linebreaks }}
{% endwith %}
Output:
<p>This is line one.<br>This is line two.</p>
<p>This is a new paragraph.</p>
2. linebreaksbr
:
- Converts every newline (
\n
) into an HTML<br>
tag, without creating paragraphs (<p>
). And keeping all text in the same flow but respecting line breaks.
Example:
{% with text="This is line one.\nThis is line two.\n\nThis is a new paragraph." %}
{{ text|linebreaksbr }}
{% endwith %}
Output:
This is line one.<br>This is line two.<br><br>This is a new paragraph.
Summary:
Use linebreaks
when you want paragraphs and linebreaksbr
when you want simple line breaks without creating paragraphs. As simple as that!
Top comments (0)