我正在使用表单发送对模板名称的响应。如何使用jinja2模板打印'route'列表元素。在下面,我同时提供了index.py页面代码和所需的输出。请向我建议应在jinja模板中使用的代码,以获取扩展的输出。
@app.route('/route',methods=['GET','POST'])
def index():
form = Route()
if request.method == 'POST':
if form.validate_on_submit():
tnum = request.form["T_No"]
r = requests.get('https://api.railwayapi.com/v2/route/train/'+request.form['T_No']+'/apikey/<myapi>/').content
return render_template('showRoute.html',form=r)
return 'something wrong'
return render_template('route.html',form=form)
"route": [
{
"no": 1,
"scharr": "SOURCE",
"schdep": "06:15",
"distance": 0,
"halt": -1,
"day": 1,
"station": {
"name": "KALKA",
"code": "KLK",enter code here
"lng": null,
"lat": null
}
}
答案 0 :(得分:0)
首先将json response转换为dict
并将其传递给模板
@app.route('/route', methods=['GET', 'POST'])
def index():
form = Route()
if request.method == 'POST':
if form.validate_on_submit():
tnum = request.form["T_No"]
r = requests.get('https://api.railwayapi.com/v2/route/train/'+request.form['T_No']+'/apikey/<myapi>/')
try:
data = r.json()
except:
data = None
return render_template('showRoute.html', data=data)
return render_template('route.html', form=form)
然后使用模板中的数据
{% if data %}
<table style="width:100%" border="3">
<tr>
{% for key in data["route"][0].keys() %}
<th>{{ key }}</th>
{% endfor %}
</tr>
{% for route in data["route"] %}
<tr>
{% for key,value in route.items() %}
{% if key == 'station' %}
<td>{{ value['name'] }}</td>
{% else %}
<td>{{ value }}</td>
{% endif %}
{% endfor %}
<br>
</tr>
{% endfor %}
</table>
{% else %}
<p>No Routes found!</p>
{% endif %}