我的代码在我的Jinja html输出中打印了一个很大的空格。然后打印所需的结果。我正在执行一个简单的select
语句,并希望显示它。我想避免(并理解为什么会这样)我的html输出中的空白。
app.py
from flask import Flask, redirect, render_template
import psycopg2
import os
import sqlalchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(12)
@app.route('/', methods=['GET', 'POST'])
def home():
engine = sqlalchemy.create_engine('postgresql://user:pw@localhost/db')
result = engine.execute('select * from person.personphone limit 10;') # adventureworks db
col_names = result.keys()
col_vals = [dict(row) for row in result]
######################################### used for debugging
for col in col_names:
print(col, end=' ')
print('')
for row in col_vals:
for col in col_names:
print(row[col], end=' ')
print('')
######################################### end debugging
return render_template('home.html', colname=col_names, colval=col_vals)
if __name__ == '__main__':
app.run(debug=True)
home.html
{% extends "base.html" %}
{% block content %}
Hello world
<br>
<div id="table">
<table>
<tr>
{% for col in colname %}
<th>{{ col }} </th>
{% endfor %}
</tr>
<br>
{% for row in colval %}
<tr>
{% for col in colname %}
<td>{{ row[col] }} </td>
{% endfor %}
</tr>
<br>
{% endfor %}
</table>
</div>
{% endblock %}
端子输出:
Jinja在浏览器上的输出:
答案 0 :(得分:1)
在表格行之间有<br>
标签,这些标签被打印在表格上方。删除它们-它们不应在那里:
<div id="table">
<table>
<tr>
{% for col in colname %}
<th>{{ col }} </th>
{% endfor %}
</tr>
{% for row in colval %}
<tr>
{% for col in colname %}
<td>{{ row[col] }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
</div>