Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print line breaks in Python Django template

{'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}}

like image 783
TIMEX Avatar asked Feb 23 '10 04:02

TIMEX


People also ask

How to line break in Django form?

As per the doc, a single newline becomes an HTML line break ( <br /> ) and a new line followed by a blank line becomes a paragraph break ( </p> ).

How to make a line break in Python?

Newline character in Python: In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.

What is {% include %} in Django?

Usage: {% extends 'parent_template. html' %} . {% block %}{% endblock %}: This is used to define sections in your templates, so that if another template extends this one, it'll be able to replace whatever html code has been written inside of it.

What is pipe in Django?

Pipeline is an asset packaging library for Django, providing both CSS and JavaScript concatenation and compression, built-in JavaScript template support, and optional data-URI image and font embedding. You can report bugs and discuss features on the issues page.


2 Answers

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

like image 130
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 07:09

Ignacio Vazquez-Abrams


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' 
like image 32
Burnash Avatar answered Sep 28 '22 07:09

Burnash