html template escape of django

Keywords: Web Development Django vim Python

The environment is the same as the django article.


Start django's web Service:

]# cd py3/django-test1/test4
]# python manage.py runserver 192.168.255.70:8000

In an html template, if the content you want to display contains html Tags:


Edit view:

]# vim bookshop/views.py
from django.shortcuts import render
from .models import *
...
def htmlTest(request):
    context = {'key1':'<h1>html Transferred meaning</h1>'}
    return render(request, 'bookshop/htmlTest.html',context)

Add html template:

]# vim templates/bookshop/htmlTest.html
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
{{ key1 }}
</body>
</html>

Add app url route:

]# vim bookshop/urls.py
from django.conf.urls import url
from .  import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(\d+)$', views.show, name='show'),
    url(r'^(\d+)/(\d+)$', views.show, name='show'),
    url(r'^index2$', views.index2, name='index2'),
    url(r'^user1', views.user1, name='user1'),
    url(r'^user2', views.user2, name='user2'),
    url(r'^htmlTest',views.htmlTest),
]

Visit browser: http://192.168.255.70:8000/htmlTest

Show:

This method is to display the variable in the html template by passing it. The value of the variable key1 is < H1 > html escape < / H1 >. In the process of passing, it is not escaped as a label, but is displayed intact.


Here's how to escape:

Modify html template: use the|safe filter to escape html

]# vim templates/bookshop/htmlTest.html
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
{{ key1}}
<hr>
{{ key1|safe}}
</body>
</html>

Browser access: http://192.168.255.70:8000/htmlTest

Show:


You can also use the {% autoescape%} label to escape the code block, literal value | default, and manual escape

To modify an html template:

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
{{ key1}}
<hr>
{{ key1|safe}}
<hr>
{% autoescape off %}
{{ key1 }}
{% endautoescape %}
<hr>
Literal
{{t2|default:'<h1>django-html Transferred meaning</h1>'}}
<br>
Manual escape:{{t2|default:'&lt;h1&gt;Transferred meaning&lt;/h1&gt;'}}
</body>
</html>

Browser access: http://192.168.255.70:8000/htmlTest

Show:

Posted by katarra on Mon, 02 Dec 2019 19:20:52 -0800