Django render_to_响应如何发送特殊字符

2024-06-09 16:22:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试图使用render_to_response方法将字符串(称为tdoc)发送到html文件。我用div标记替换了字符串中的“spc”标记。假设在替换之后,字符串的一部分是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;  
}  

所以,我应该看到单词examine是粗体和黄色背景的,但是我没有看到。当我查看呈现的html的源代码时,它有以下子字符串We would seldom be prepared to &lt;div id=&quot;spcl&quot;&gt;examine&lt;/div&gt; every,而不是原来的字符串。在

如何使单词“examine”和类似的单词以所需的方式显示?在


Tags: 文件to字符串标记divresponsehtmlrender
1条回答
网友
1楼 · 发布于 2024-06-09 16:22:49

使用^{}防止html转义:

from django.utils.safestring import mark_safe

...

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

或在模板中使用^{}筛选器:

^{pr2}$

示例:

>>> 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>

相关问题 更多 >