Allowing
tags with Google App Engine and Jinja2

后端 未结 8 1671
粉色の甜心
粉色の甜心 2021-01-04 22:11

In my web app, the user can make blog posts. When I display the blog post, newlines aren\'t shown because I didn\'t replace the new lines with
tags.

相关标签:
8条回答
  • 2021-01-04 22:55

    The solution was to put <pre></pre> tags around the area where I had the content.

    0 讨论(0)
  • 2021-01-04 22:58

    You can create a jinja2 filter:

    import re
    from jinja2 import evalcontextfilter, Markup, escape
    
    _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
    
    @evalcontextfilter
    def nl2br(eval_ctx, value):
        result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
                              for p in _paragraph_re.split(escape(value)))
        if eval_ctx.autoescape:
            result = Markup(result)
        return result
    

    You need to add the filter to your jinja2 Environment before you can use it:

    JINJA2_ENV.filters['nl2br'] = jinja2_filters.nl2br
    

    In your template you can use that filter:

    {{post.content|nl2br}}
    
    0 讨论(0)
提交回复
热议问题