【问题标题】:Is is possible to html encode output in AppEngine templates?是否可以在 AppEngine 模板中对输出进行 html 编码?
【发布时间】:2010-10-27 17:02:56
【问题描述】:

所以,我传递了一个带有“内容”属性的对象,该属性包含 html。

<div>{{ myobject.content }}</div>

我希望能够输出内容,以便将字符呈现为 html 字符。

“内容”的内容可能是:

Hello

我希望将其发送到浏览器:&amplt;p&ampgt;Hello&amplt;/p>

我可以在我的模板中添加一些东西来自动执行此操作吗?

【问题讨论】:

    标签: django templates django-templates html-encode


    【解决方案1】:

    是的,{{ myobject.content | escape }} 应该会有所帮助(假设您指的是 Django 模板——没有特定的“App Engine”模板系统,GAE 应用程序通常使用 Django 模板系统);如果您想要两个级别的转义,您可能需要重复 | escape 部分(在您提供的某些但不是全部示例中似乎是这种情况)。

    【讨论】:

    • 我的小应用正在使用 Google 的 webapp 框架。但我认为该框架确实默认使用 Django 模板系统。
    【解决方案2】:

    这是 Django 的 django.utils.html.escape 函数:

    def escape(html):
        """Returns the given HTML with ampersands, quotes and carets encoded."""
        return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l
    t;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))
    

    另外,请参阅here

    【讨论】:

      猜你喜欢
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      • 2011-12-16
      相关资源
      最近更新 更多