Jinja render text in HTML preserving line breaks

后端 未结 3 1579
旧时难觅i
旧时难觅i 2020-11-30 12:15

I have a simple form like this:

class RecordForm(Form):    
    notes = TextAreaField(\'Notes\')

I record the data in three paragraphs like

3条回答
  •  时光取名叫无心
    2020-11-30 13:07

    I've modified nl2br filter from documentation according to this https://stackoverflow.com/a/60572523/12851576 answer:

    import re
    from jinja2 import evalcontextfilter
    from markupsafe import Markup, escape
    
    
    @evalcontextfilter
    def nl2br(eval_ctx, value):
        """Converts newlines in text to HTML-tags"""
        result = "
    ".join(re.split(r'(?:\r\n|\r|\n)', escape(value))) if eval_ctx.autoescape: result = Markup(result) return result

    It works for me. Are there any drawbacks?

提交回复
热议问题