【问题标题】:django render_to_response how to send special charactersdjango render_to_response 如何发送特殊字符
【发布时间】:2013-09-13 14:51:59
【问题描述】:

我有一个要显示在 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 <div id="spcl">examine</div> every 而不是原始字符串。

如何使“检查”一词和类似的词以所需的方式显示?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 太棒了,我自己写得再好不过了。那假设,我可以! :P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多