Lisa
Lisa

Reputation: 43

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?

Upvotes: 4

Views: 384

Answers (2)

goldstein
goldstein

Reputation: 467

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)

Upvotes: 1

JamesO
JamesO

Reputation: 25956

striptags filter removes all html

{{object.name|striptags}}

Upvotes: 7

Related Questions