使用 Jinja 在呈现为 HTML 的文件中保留换行符

Preserve newlines in file rendered to HTML with Jinja

我正在尝试打印网页中文件的内容。我想在单独的行上打印文件中的每一行,但缺少换行符。如何打印文件并保留换行符?

@app.route('/users')
def print_users():
    v = open("users.txt","r").read().strip()
    # also tried:
    # v = open("users.txt","r").read().strip().split('\n')
    return render_template('web.html', v=v)
{{ v|safe}}

您可以使用:

v = open("users.txt","r").readlines()
v = [line.strip() for line in v]

然后在您的 html 中(但请随意使用):

<form action="/print_users"  method="post" >    
                    <div class="form-inline">

                  {% for line in v %}
                      <div>{{ line|safe}}</div>
                  {% endfor %}


    <input class="btn btn-primary" type="submit"  value="submit" > 
              </div>

                    </form> 

虽然其他答案提供了很好的技术并且当前接受的解决方案有效,但我需要执行类似的任务(呈现文本电子邮件模板),但需要扩展它以保留文件中宏的处理,这引导我创建我认为最简单和最优雅的解决方案 - 使用 render_template_string.

def show_text_template(template_name):
    """
    Render a text template to screen.
    Replace newlines with <br> since rendering a template to html will lose the line breaks
    :param template_name: the text email template to show
    :return: the text email, rendered as a template
    """
    from flask import render_template_string

    txt_template = open(
        '{}/emails/{}{}'.format(app.config.root_path + '/' + app.template_folder, template_name, '.txt'),
        "r").readlines()

    return render_template_string('<br>'.join(txt_template))