How to print line breaks in Python Django template
Use the linebreaks
filter.
For example:
{{ value|linebreaks }}
If value is Joel\nis a slug
, the output will be <p>Joel<br />is a slug</p>
.
You can also use the linebreaksbr
filter to simply convert all newlines to <br>
without additional <p>
.
Example:
{{ value|linebreaksbr }}
If value
is Joel\nis a slug
, the output will be Joel<br>is a slug
.
The difference from Ignacio's answer (linebreaks
filter) is that linebreaks
tries to guess the paragraphs in a text and wrap every paragraph in <p>
where linebreaksbr
simply substitutes newlines with <br>
.
Here's a demo:
>>> from django.template.defaultfilters import linebreaks>>> from django.template.defaultfilters import linebreaksbr>>> text = 'One\nbreak\n\nTwo breaks\n\n\nThree breaks'>>> linebreaks(text)'<p>One<br />break</p>\n\n<p>Two breaks</p>\n\n<p>Three breaks</p>'>>> linebreaksbr(text)'One<br />break<br /><br />Two breaks<br /><br /><br />Three breaks'
All of these answers don't explicitly mention that {{ value|linebreaksbr }}
should be used in the display template ie the get request not the post request.
So if you had a template to display say post.details, it would be
<h4>Below are the post details</h4>{{ post.details|linebreaksbr }}
And not in the post form
<form method="post"> {% csrf_token %} {{ form|linebreaksbr }} <button>Save post</button></form>
Had this same issue and after figuring it our decided that someone outthere might find it handy.Happy coding!