Django does not display newline when rendering text from database

I use Django for development, getting some text containing a newline from the database. However, when I do it with a template using the template tag, it does not display a newline character.

What is the problem?

+64
html newline django-templates
Aug 31 '09 at 6:18
source share
2 answers

You must remember that your templates create HTML. In HTML, the newline is just another blank space, this does not mean that the following text should be added to the newline. There are several ways to force the creation of new lines in HTML.

You can wrap the text with a <pre> tag so that HTML understands that it is pre-formatted:

 <pre>{{value}}</pre> 

You can use Django filters to convert strings to text strings in HTML. linebreaks turns single newlines into <br> tags and double newlines into <p> tags. linebreaksbr just turns newlines into tags <br> :

 {{value|linebreaks}} {{value|linebreaksbr}} 

You can experiment with them to see what you like best.

Otherwise, you can use string manipulation in your view to convert your plain text to HTML in a way that suits you. And if you want to become truly advanced, you can write your own filter that converts what you like and use it in all templates.

+156
Aug 31 '09 at 10:29
source share

Not sure if I fully understand your question, but try using the linebreaks filter.

 {{ value|linebreaks }} 
+14
Aug 31 '09 at 6:23
source share



All Articles