Simrandeep Singh
Simrandeep Singh

Reputation: 11

Display contents of a text file in Django template

I am attempting to create a file in simple website and then read the contents of the same in a variable inside a Django view function and parse the variable to the template to be displayed on web page. However, when I print the variable, it appears the same on cmd as is in the original text file, but the output on the web page has no formattings but appears like a single string.

I've been stuck on it for two days.

Also I'm relatively new to django and self learning it

file1 = open(r'status.txt','w',encoding='UTF-8')
file1.seek(0)
for i in range(0,len(data.split())):

        file1.write(data.split()[i] + "          ")
        if i%5==0 and i!=0 and i!=5:
        file1.write("\n")
        file1.close()

file1 = open(r'status.txt',"r+",encoding='UTF-8')
d = file1.read()
print(d) #prints on cmd in the same formatting as in text file
return render(request,'status.html',{'dat':d}) **#the html displays it only as a single text 
string**
<body>

{% block content %}

        {{dat}}

{% endblock %}

</body>

Link to image with html page display

Upvotes: 0

Views: 3886

Answers (3)

Nicolas Appriou
Nicolas Appriou

Reputation: 2331

Depending of your needs and the file format you want to print, you may also want to check the <pre> HTML tag.

Upvotes: 0

Nalin Dobhal
Nalin Dobhal

Reputation: 2342

Use the linebreaks filter in your template. It will render \n as <br/>.

use it like -: {{ dat | linebreaks }}

from the docs:

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

You can use linebreaksbr if you don't want <p> tag.

Upvotes: 1

Igor Alex
Igor Alex

Reputation: 1121

It's because in HTML newline is </br> in Python it is \n. You should convert it, before rendering

mytext = "<br />".join(mytext.split("\n"))

Upvotes: 0

Related Questions