用Python创建动态表格

12

我正在开发一个小网站,需要从API获取一些数据并在表格中显示出来(我不知道需要多少行,这取决于API)。我选择Python作为后端编程语言,使用Flask作为Web框架。我需要在页面启动时从Python向API发出请求,并在HTML模板中显示其结果。使用render_template和一些参数无法实现 - 因为它无法动态显示HTML元素,只能显示文本。如何在没有JS / JQuery或最小使用的情况下完成它?这是我的表格代码(它使用Bootstrap 4)

<table class="table table-bordered" id="users">
  <thead>
    <tr>
      <th>ID</th>
      <th>Имя</th>
      <th>Фамилия</th>
      <th>Действие</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td rowspan="1">3319</td>
      <td>...</td>
      <td>...</td>
      <td><a href="#">Выбрать</a></td>
  </tbody>
</table>


你可以在使用Flask的render_template渲染HTML文件时使用Jinja2。 - yeg
3个回答

10
使用Jinja2时,您可以使用Jinja2的编程功能动态创建表格,其语法与Python非常相似。
<table>
 <thead>
  {%- for column in columns %}
     <th>{{ column }}</th>
  {%- endfor %}
 </thead>

 <tbody>
 {%- for row in items %}
    <tr>
    {%- for column in columns %}
       <td>{{ row|attr(column) }}</td>
    {%- endfor %}
    </tr>
 {%- endfor %}
 </tbody>
 </table>
在调用render_template时,需要提供两个变量:“columns”包含行的列列表,“items”包含行。
不需要使用JS。
如果您想支持某些特殊数据类型(例如链接),可以在模板中使用if语句来实现。
有关更多详细信息,请参见Jinja2的参考文档: http://jinja.pocoo.org/docs/2.10/templates/

使用这段代码,Jinja2会报错:jinja2.exceptions.UndefinedError: 'attr' is undefined。如果我将attr(row, column)替换为row[column],则只会显示两行空表格。 - crinny
@crinny:我想我理解错了--attr是一个过滤器。 试试这个:{{ row|attr(column) }} - Juergen
@juegern 和 row[column] 一样的结果。我的代码:return render_template('desk.html', columns=['Id', 'Test'], items=['1', 'test str']) - crinny
@crinny:Items必须是一系列行的列表。您这里拥有的是一系列单值。您是否使用SQLAlchemy或类似工具? - Juergen
@juegern 不,我目前没有使用任何数据库。 - crinny

10

你可能也对这个模式感兴趣,使用Python包Pandas:

import pandas as pd

@app.route('/table')
def display_table():
    # do something to create a pandas datatable
    df = pd.DataFrame(data=[[1,2],[3,4]])
    df_html = df.to_html()  # use pandas method to auto generate html
    return render_template('page.html', table_html=df_html)

然后在 page.html 中包含以下内容:

{{ table_html | safe }}

您需要包含safe过滤器,这样它可以呈现原始的HTML内容而不会转义任何字符。

这将呈现以下内容,您还可以使用pandas中提供的参数和样式来进行样式化。

<table border="1" class="dataframe">  
<thead>    
<tr style="text-align: right;">      
<th></th>    
<th>0</th>      
<th>1</th>    
</tr>  
</thead>  
<tbody>    
<tr>      
<th>0</th>     
<td>1</td>     
<td>2</td>   
</tr>    
<tr>      
<th>1</th>    
<td>3</td>     
<td>4</td>    
</tr> 
</tbody>
</table>

编辑:FYI,这对于您具有复杂或动态条件格式的问题也非常方便,该问题在python / pandas服务器端上更容易样式化,而无需担心html模板。当然这取决于您正在做什么,但我认为在某些情况下,这更可维护-就像我的情况一样!



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接