Django Doesn't Display Newline Character When Rendering Text from Database

Django doesn't display newline character when rendering text from database

You have to remember that your templates are producing HTML. In HTML, a newline character is just another white space, it doesn't mean to put the following text onto a new line. There are a number of ways to force new lines in HTML.

You can wrap your text with a <pre> tag so that HTML will understand that it is preformatted:

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

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

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

You can experiment with these to see which you like better.

Failing that, you can use string manipulation in your view to convert your plain text into HTML in a way that suits you better. And if you want to get really advanced, you can write your own filter that converts the way you like, and use it throughout your templates.

newline in models.TextField() not rendered in template

linebreaks

Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br />) and a new line followed by a blank line becomes a paragraph break (</p>).

For example:

{{ value|linebreaks }}

Django: show newlines from admin site?

Use the linebreaks template filter.

Is there any way to allow \n in a django template? (bootstrap-popover)

Use the autoescape template tag to escape HTML linebreak (<br />) characters.

In addition, since you do not have html linebreak characters, you have to convert your text file newlines to HTML linebreaks, using the linebreaksbr Django template filter, as suggested in this answer.

Your code should look like:

{% autoescape on %}
{{ contact.info | linebreaksbr }}
{% endautoescape %}

Is there any way to allow \n in a django template? (bootstrap-popover)

Use the autoescape template tag to escape HTML linebreak (<br />) characters.

In addition, since you do not have html linebreak characters, you have to convert your text file newlines to HTML linebreaks, using the linebreaksbr Django template filter, as suggested in this answer.

Your code should look like:

{% autoescape on %}
{{ contact.info | linebreaksbr }}
{% endautoescape %}

Different lines does not appear in context in Django

You can make use of the |linebreaks template filter [Django-doc]:

{{ hellos|linebreaks }}

This will transform the hellos to:

>>> Template('{{ hellos|linebreaks }}').render(Context(context))
'<p>hello Earth <br> hello Mars</p>'

or you can make use of the |linebreaksbr template filter [Django-doc] to only add <br>s without the paragraphs <p>:

>>> Template('{{ hellos|linebreaksbr }}').render(Context(context))
'hello Earth <br> hello Mars'


Related Topics



Leave a reply



Submit