Allowing
tags with Google App Engine and Jinja2

后端 未结 8 1731
粉色の甜心
粉色の甜心 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: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'

    %s

    ' % p.replace('\n', '
    \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}}
    

提交回复
热议问题