我正在尝试在网页中打印文件的内容。我想在单独的行上打印文件中的每一行,但缺少换行符。如何打印文件并保留换行符?
@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}}
答案 0 :(得分:2)
您可以使用:
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>
答案 1 :(得分:0)
虽然其他答案提供了很好的技术并且当前接受的解决方案有效,但我需要执行类似的任务(渲染文本电子邮件模板),但需要对此进行扩展以保留文件中宏的处理,这导致我创建我认为最简单和最优雅的解决方案 - 使用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))