保留与Jinja呈现为HTML的文件中的换行符
问题描述:
我试图在网页中打印文件的内容。我想在单独的行上打印文件中的每一行,但是缺少换行符。如何打印文件并保留换行符?保留与Jinja呈现为HTML的文件中的换行符
@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>
+0
这个工程!谢谢! – chahra
答
而其他的答案给予伟大的技术和当前接受的解决方案的作品,我需要做一个类似的任务(呈现一个文本电子邮件模板),但需要延长t他在文件中保留宏的处理,这使我创建了我认为最简单和最优雅的解决方案 - 使用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))
使用'readlines()'获取行列表 –
但是如何分别打印每行?任何代码示例? – chahra
把一个for循环放在你的html中 –