django render_to_response如何发送特殊字符

时间:2013-09-10 02:09:23

标签: python css django django-templates render-to-response

我有一个要在html文件中显示的字符串。字符串中的某些单词(标记为" spc")需要以黄色背景和较大的字体显示。

我试图使用render_to_response方法将字符串(称为tdoc)发送到html文件。我取代了&#39; spc&#39;带有div标签的字符串中的标签。假设,在替换后,部分字符串为we would seldom be prepared to <div id="spcl">examine</div> every。我的django代码看起来像render_to_response('a.html',{'taggeddoc':tdoc})

在我的CSS中,我有以下代码

 #spcl {  
background-color: #FFFF00;  
font-size:15px;  
}  

所以,我应该用粗体字和黄色背景看到检查这个词,但我不明白。当我查看渲染的html的源时,它有以下子串We would seldom be prepared to &lt;div id=&quot;spcl&quot;&gt;examine&lt;/div&gt; every而不是原始字符串。

我怎样才能说出“检查”这个词。和类似的单词以所需的方式显示?

1 个答案:

答案 0 :(得分:5)

使用mark_safe阻止html转义:

from django.utils.safestring import mark_safe

...

render_to_response('a.html', {'taggeddoc': mark_safe(tdoc)})

或在模板中使用safe过滤器:

{{ taggeddoc|safe }}

示例:

>>> from django.utils.safestring import mark_safe
>>> from django.template import Template, Context

# without mark_safe, safe
>>> print(Template('{{ taggeddoc }}').render(Context({'taggeddoc': '<div>hello</div>'})))
&lt;div&gt;hello&lt;/div&gt;

# mark_safe
>>> print(Template('{{ taggeddoc }}').render(Context({'taggeddoc': mark_safe('<div>hello</div>')})))
<div>hello</div>

# safe filter
>>> print(Template('{{ taggeddoc|safe }}').render(Context({'taggeddoc': '<div>hello</div>'})))
<div>hello</div>
相关问题