简体   繁体   中英

Django template question: how to output just the text if the variable has html in it?

I have a lot of variables that has html in them. For example the value of a variable called {{object.name}} is the following:

Play this <a href="#">hot</a> game and see how <b>fun</b> it is!

Is there a filter that can be applied on the variable that will give me just the text:

Play this hot game and see how fun it is!

Without the text being linked or the html being replaced by htmlentities. Just the text?

striptags filter removes all html

{{object.name|striptags}}

You have 3 options to strip the html code:

Using " safe " filter in your template:

{{ object.name|safe }}

Using " autoescape " tag in your template:

{% autoescape off %}
{{ object.name }}
{% endautoescape %}

or declaring it as " safe " in your python code:

from django.utils.safestring import mark_safe
name = mark_safe(name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM