简体   繁体   中英

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.
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. Is there anything like a HTML tag to do that?

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; . The second option is using <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>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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