DEV Community

DoriDoro
DoriDoro

Posted on

What is the difference between the template filter: `|linebreaks` and `|linebreaksbr` in Django Template?

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:
html
{% with text="This is line one.\nThis is line two.\n\nThis is a new paragraph." %}
{{ text|linebreaks }}
{% endwith %}

Output:
`html

This is line one.
This is line two.

This is a new paragraph.

`

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:
html
{% with text="This is line one.\nThis is line two.\n\nThis is a new paragraph." %}
{{ text|linebreaksbr }}
{% endwith %}

Output:
html
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)