如何让bootstrap-table-filter-control与Flask、Jinja和Dataframe一起使用

4
我会尽力帮助您翻译中文内容,以下是所需翻译的内容:

我正在使用python Flask的render_template方法为我的python应用程序的路由返回一个html页面,在该html页面中,我想使用bootstrap-table-filter-control功能,就像bootstrap的这个示例中描述的那样。然而,该示例似乎使用了来自本地json文件的表格。以下是该示例中给出的代码:

<link href="https://unpkg.com/bootstrap-table@1.16.0/dist/bootstrap-table.min.css" rel="stylesheet">

<script src="https://unpkg.com/bootstrap-table@1.16.0/dist/bootstrap-table.min.js"></script>
<script src="https://unpkg.com/bootstrap-table@1.16.0/dist/extensions/filter-control/bootstrap-table-filter-control.min.js"></script>

<table
  id="table"
  data-url="json/data1.json"   ## this looks like the code to get the table's data
  data-filter-control="true"
  data-show-search-clear-button="true">
  <thead>
    <tr>
      <th data-field="id">ID</th>
      <th data-field="name" data-filter-control="input">Item Name</th>
      <th data-field="price" data-filter-control="select">Item Price</th>
    </tr>
  </thead>
</table>

<script>
  $(function() {
    $('#table').bootstrapTable()
  })
</script>

我该如何用我的Python数据框架替换主程序main.py传递的表格中的

data-url="json/data1.json"

?我尝试使用以下 HTML 代码进行替换,但未成功:

        {% for table in tables %}
            <table id="table"
                data = {{ table|safe }}
                data-filter-control="true"
                data-show-search-clear-button="true"
                class="table-striped">

                <thead>
                    <tr>
                        <th data-field="columnA" data-filter-control="input">column A</th>
                        <th data-field="columnB" data-filter-control="select">columnB</th>
                        <th data-field="columnC" data-filter-control="select">columnC</th>
                    </tr>
                </thead>
                <tbody>
                   <!-- I have tried to put {{ table|safe }} here but doesn't work -->
                </tbody>
            </table>
        {% endfor %}

我的Python路由看起来像这样:

@app.route('/')
def hello():
    return render_template('yield.html',  tables=[df3.to_html(classes='data', header="true")])

其中df3是我想在yield.html中用bootstrap筛选控件显示为表格的数据框。

2个回答

7
在进行一些基础逐步测试后,我找到了自己的解决方案,现在它已经像魅力一样工作了。我的yield.html文件如下所示,启用了bootstrap-table筛选控件、搜索和排序功能:
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 <!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.16.0/dist/bootstrap-table.min.css">  
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/extensions/filter-control/bootstrap-table-filter-control.css">
  </head>
  <body>
    <div class="container">
                <table id="table"
                    data-toggle="table"
                    data-filter-control="true"
                    data-show-search-clear-button="true"
                    data-sortable="true"
                    classes="table-sm"
                    data-pagination="true"
                    data-show-columns="true"
                    data-show-columns-toggle-all="true"
                    class="table-responsive">
                    <thead>
                        <tr>
                            <!--special characters and spaces not allowed in data-field name-->
                            <th data-field="columnA" data-filter-control="input" data-sortable="true">column A</th>
                            <th data-field="columnB" data-filter-control="select" data-sortable="true">column B</th>
                            <th data-field="columnC" data-filter-control="input" data-sortable="true">column C</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for row in tableA %}
                        <tr>
                            <!--special characters and spaces not allowed in data-field name-->
                            <td>{{ row.columnA }}</td>
                            <td>{{ row.columnB }}</td>
                            <td>{{ row.columnC }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
    </div>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/bootstrap-table@1.16.0/dist/bootstrap-table.min.js"></script>
    <script src="https://unpkg.com/bootstrap-table@1.16.0/dist/extensions/filter-control/bootstrap-table-filter-control.min.js"></script>
</body>
</html>

值得注意的是,在我的 main.py 应用程序中,我不是调用完整的包含表头和行标签的 HTML 表格,而是需要具体指定表头 (在 thead 标签内) 和每个列的参数清晰地说明。表头的数据字段名不能包含空格和特殊字符,然后使用 {% for row in tableA %} 和相应的列名称来提取数据行。
在我的 Python 应用程序中,我的数据来自于一个 DataFrame,我需要将其转换为 Python 数据类型,具体来说是类似于列表的 Python 字典,使用 data = df.to_dict('records'),当我渲染模板时,可以使用 return render_template('yield.html', tableA = data) 将这个字典传递给模板。
我的 Python 应用程序路由如下:
@app.route('/')
def hello():
    data = df.to_dict('records')
    return render_template('yield.html', tableA = data)

你用这个例子改变了我的生活,哈哈。有很多用途!谢谢你! - Rob Thompson

2
一个使用Bootstrap-table和Flask的简单示例。
结构:
├── app.py
└── templates
    └── table.html

Table.html:


<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex">
  <title>Bootstrap Table - Flask example </title>
  <script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
  <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css">
  <script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
  <style type='text/css'>
    .row-index {
      width: 50px;
      display: inline-block;
    }
  </style>

  <script type='text/javascript'>
    $(window).load(function(){
      var data = {{data|tojson}};
      var columns = {{columns|tojson}};

      $(function() {
        $('#table').bootstrapTable({ 
          data: data,
          columns: columns,
        });

      });

    });
  </script>
</head>
<body>
  <div class="container" style="padding: 10px; ">
    <h1>{{title}}</h1>
    <br/>
    <div id="toolbar"></div>
    <table
      id="table"
      data-toggle="true"
      data-toolbar="#toolbar"
      data-search="true"
      data-show-columns="true"
      data-pagination="true"
      data-height="500">
    </table>
  </div>
</body>
</html>

app.py:

from flask import Flask, render_template
import json

"""
A example for creating a Table that is sortable by its header
"""

app = Flask(__name__)
data = [{
  "name": "bootstrap-table",
  "commits": "10",
  "attention": "122",
  "uneven": "An extended Bootstrap table"
},
 {
  "name": "multiple-select",
  "commits": "288",
  "attention": "20",
  "uneven": "A jQuery plugin"
}, {
  "name": "Testing",
  "commits": "340",
  "attention": "20",
  "uneven": "For test"
}]
# other column settings -> http://bootstrap-table.wenzhixin.net.cn/documentation/#column-options
columns = [
  {
    "field": "name", # which is the field's name of data key 
    "title": "name", # display as the table header's name
    "sortable": True,
  },
  {
    "field": "commits",
    "title": "commits",
    "sortable": True,
  },
  {
    "field": "attention",
    "title": "attention",
    "sortable": True,
  },
  {
    "field": "uneven",
    "title": "uneven",
    "sortable": True,
  }
]

#jdata=json.dumps(data)

@app.route('/')
def index():
    return render_template("table.html",
      data=data,
      columns=columns,
      title='Flask Bootstrap Table')


if __name__ == '__main__':
    #print jdata
  app.run(debug=True)

输出: 在这里输入图片描述 参考:bambooom

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