简体   繁体   English

在 Jinja2 中禁用自动转义后重新启用自动转义

[英]Re-enable autoescape after it has been disabled in Jinja2

I'm writing a simple blog using Flask and Jinja2, and I want to use HTML tags in my posts.我正在使用 Flask 和 Jinja2 写一个简单的博客,我想在我的帖子中使用 HTML 标签。
So I was disabled the autoescape in my templates like this:所以我在我的模板中禁用了自动转义,如下所示:

{{ post.body|safe }}

But when I writing something like >>> print() or it's , however I don't want to escape them myself, I want to enable the autoescape again.但是当我写类似>>> print()it's ,但是我不想自己转义它们,我想再次启用自动转义 Is there anything like a HTML tag to do that?有没有像 HTML 标签那样的东西来做到这一点?

Well, if you want to use HTML in your post.body - then you have to deal with the fact that some symbols have to be escaped in HTML, eg > should be &gt;好吧,如果你想在你的post.body使用 HTML - 那么你必须处理一些符号必须在 HTML 中转义的事实,例如>应该是&gt; . . The second option is using <pre> .第二个选项是使用<pre> The third option is post-processing the body, so that the code parts like >>> are automatically escaped.第三个选项是对正文进行后处理,以便自动转义>>>类的代码部分。 For example:例如:

class Post:
    body = "<span><code>>>> print('Hello world')</code></span>"

    @property
    def html_body(self):
        # 1. Locate all <code>...</code> blocks
        # 2. Convert the text in them to proper HTML
        ...
        return processed_body

    # which should return 
    # "<span><code>&gt;&gt;&gt; print(&apos;Hello world&apos;)</code></span>"

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

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