Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing html code from views to template in Django

I have an html-table generated in views.py. I want to show it in my html template. If I pass the html code as a string, symbols like "<" are automatically substituted to "& lt;", so instead of the table I see its html code. How can I solve this problem?

like image 803
George Avatar asked Dec 04 '22 22:12

George


1 Answers

Just have to escape html var with |safe filter as follows

In your views.py

....
context['your_html_variable '] = "<div><h1> Hello </h1></div>"
return render(request, 'template.html', context)

In your template.html

<body>
    {{ your_html_variable|safe }}
</body>

Be Careful ! Never try to escape html variable when it comes from user, not you.

like image 50
1ronmat Avatar answered Jun 28 '23 08:06

1ronmat