我创建了以下 Flask webapp(如下)。它以表格格式在页面上输出一个简单的数据框。
我试图让表格中的第一列 (name
) 可点击,并且使用列 Linkdid
值作为后缀创建的链接。
具体来说,数据帧中的 Bob 将有一个 client_details/111111
的链接,随后的每一行都将获得其对应的 linkid 并按照以下格式创建相应的链接:client_details/{linkid}
:
<a href="#" target="popup" onclick="window.open('client_details/{linkid}','name','width=600,height=400')">{{row_}}</a>
如何获取循环中的 linkid
列值来构造这样的东西?我还计划在某个时候隐藏 linkid 列。
这是我目前所拥有的:
app.py
import os
import pandas as pd
import datetime as dt
from flask import Flask, render_template, url_for, request, jsonify
import sys
df = pd.DataFrame({'Name': ['Bob','Carl','Doug','Edith','Ford','George']
, 'Amount': ['17','123','144','2','63','25']
, 'Quantity': ['147','1523','1144','542','5463','2135']
, 'Linkid': ['111111','2311231233','4142421','4124214','52435435','2535325']
})
@app.route("/")
def homePage():
return render_template('index.html', column_names=df.columns.values, row_data=list(df.values.tolist()), zip=zip)
index.html
<table id="customer_df" class="display">
<thead class="text-primary">
<tr>
{% for col in column_names %}
<th class="text-center">
{{col}}
</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in row_data %}
<tr>
{% for col, row_ in zip(column_names, row) %}
{% if loop.index == 1 %}
<td><a href="#" target="popup" onclick="window.open('client_details/','name','width=600,height=400')">{{row_}}</a></td>
{% else %}
<td>{{row_}}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
答案 0 :(得分:0)
尝试使用 pandas
方法,它会让您更轻松,使用可以传递给 df.to_html
方法的 formatters
,您最终会得到类似以下内容:>
1 - 为您的 lambda
列创建一个 Linkid
函数:
link_frmt = lambda x: '''<a href="#" target="popup"
onclick="window.open('client_details/{0}',
'name','width=600,height=400')">{0}</a>'''.format(x)
2 - 然后您可以像这样将 df.to_html
的结果传递给 render_template
:
render_template('index.html',
table=df.to_html(
formatters={'Linkid':link_frmt},
escape=False
)
)
此外,在此阶段,您可以使用 classes='my_css_table
中的 df.to_html
传递特定的 CSS 样式:
render_template('index.html',
table=df.to_html(
formatters={'Linkid':link_frmt},
escape=False,
classes='my_css_table'
)
)
3 - 最后在您的模板中执行:
{{ table|safe }}
这将创建整个表格并正确呈现。
您可以为 df 表使用 CSS 样式:
table.dataframe, .dataframe th, .dataframe td {
border: none;
border-bottom: 1px solid #C8C8C8;
border-collapse: collapse;
text-align:left;
padding: 10px;
margin-bottom: 40px;
font-size: 0.9em;
}