Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape {{ or }} in django template?

Tags:

python

django

Django treats {{ var }} as some variable in its template. How can I escape {{ var }} or {{ or }} such that django does not treat it as variable.

<p>"{{ some text }}"</p> Should prints exactly the same.

like image 936
Tauquir Avatar asked Oct 14 '11 18:10

Tauquir


People also ask

How do I escape a Django template?

Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the {% templatetag %} tag.

What does {{ name }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

How do you turn off Django's automatic HTML escaping?

For example, you can check if my_textfield contains a script tag. If so, mark the instance as malicious and return an escaped version of my_textfield (the normal Django behavior). Otherwise, use mark_safe to return your HTML code marked as safe.


2 Answers

Django 1.5 introduced {% verbatim %} template tag. It stops template from parsing contents of this tag:

{% verbatim %}     {{ var }} {% endverbatim %} 

will be rendered as:

{{ var }} 
like image 124
Ondrej Slinták Avatar answered Oct 01 '22 13:10

Ondrej Slinták


I believe you are looking for the templatetag template tag.

As the linked-to doc states,

Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the {% templatetag %} tag.

For example:

<p>"{% templatetag openvariable %} some text {% templatetag closevariable %}"</p> 

will appear as so:

<p>"{{ some text }}"</p> 
like image 23
Nate Avatar answered Oct 01 '22 12:10

Nate