How to print line breaks in Python Django template


Question

{'quotes': u'Live before you die.\n\n"Dream as if you\'ll live forever, live as if you\'ll die today"\n\n"Love one person, take care of them until you die. You know, raise kids. Have a good life. Be a good friend. Try to be completely who you are, figure out what you personally love and go after it with everything you\'ve got no matter how much it takes." -Angelina Jolie.'}

Notice my dictionary has line breaks in them: \n

How do I display my template with those line breaks?

{{quotes|withlinebreaks\n}}

1
23
2/23/2010 4:03:34 AM

Accepted Answer

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>.

59
6/1/2017 1:46:31 PM

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'

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon