Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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?

like image 996
Lisa Avatar asked Feb 23 '23 21:02

Lisa


2 Answers

striptags filter removes all html

{{object.name|striptags}}

like image 84
JamesO Avatar answered Feb 26 '23 20:02

JamesO


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)
like image 22
goldstein Avatar answered Feb 26 '23 21:02

goldstein