简体   繁体   English

Django模板问题:如果变量中有html,如何只输出文本?

[英]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. 我有很多变量,其中包含html。 For example the value of a variable called {{object.name}} is the following: 例如,名为{{object.name}}的变量的值如下:

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. 没有文本链接或html被htmlentities取代。 Just the text? 只是文字?

striptags filter removes all html striptags过滤器删除所有html

{{object.name|striptags}} {{object.name | striptags}}

You have 3 options to strip the html code: 您有3个选项来删除HTML代码:

Using " safe " filter in your template: 在模板中使用“ 安全 ”过滤器:

{{ object.name|safe }}

Using " autoescape " tag in your template: 在模板中使用“ autoescape ”标记:

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

or declaring it as " safe " in your python code: 或者在python代码中将其声明为“ 安全 ”:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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