如何在数据表中显示python数组?

irlmq6kh  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(293)

我使用的是flask,我从数据库中读取了一个数组,数组看起来像[[“customer”,“address”,“ppl”],[“customer2”,“address2”,“ppl2”]]
使用datatables插件,我希望“customer”和“customer2”显示在customer列中,“address”和“address2”显示在address列中,“ppl”和“ppl2”显示在ppl列中。我可以用html中的for循环来实现这一点,但是这会弄乱我的datatable格式,并从表中删除搜索框和prev/next按钮。如何获得这些值来填充数据表中的单元格?
python代码:

def hello():

mariadb_connection = mariadb.connect(user='root', password='pwd', 
database='customers')
cursor = mariadb_connection.cursor()

cursor.execute("SELECT * from customer_info")
data = cursor.fetchall()
cursor.close()

namesdb = json.dumps(data)

return render_template('select_customer.html', namesdb=namesdb)

html格式:

<table id="example" class="table text-dark table-striped table-bordered 
  display" style="width:100%">

    <thead class="text-white">

        <tr>

            <th>Customer</th>

            <th>Address</th>

            <th>Price per Litre</th>

        </tr>

    </thead>

    <tbody>

    <tr>

            <td>{{namesdb}}</td>

            <td></td>

            <td></td>

        </tr>

    </tbody>

    <tfoot>

        <tr>

        </tr>

    </tfoot>

</table>

</div>
</div>
</div>

 </div>
</div>

我被链接到这篇文章,如何构造数据以轻松地在flask中构建html表,
但是如前所述,使用这个for循环填充datatables表中的列,但是for循环似乎删除了搜索框和prev/next按钮。
脚本.js

$(document).ready(function() {
 var table = $('#example').DataTable();
 $('#example tbody').on( 'click', 'tr', function () {
     $(this).toggleClass('selected');
  } );

 $('#button').click( function () {

alert( table.rows('.selected').data().length +' 
 row(s) selected' );

 } );

 } );
9w11ddsr

9w11ddsr1#

首先,不要在json.dump将数据发送到模板之前转储它。

def hello():

    mariadb_connection = mariadb.connect(user='root', password='pwd', 
    database='customers')
    cursor = mariadb_connection.cursor()

    cursor.execute("SELECT * from customer_info")
    namesdb = cursor.fetchall()
    cursor.close()

    return render_template('select_customer.html', namesdb=namesdb)

只需使用jinja中元组的pythonic列表。

{%- for item in namesdb -%}
<tr>
    <td>{{ item[0] }}</td>
    <td>{{ item[1] }}</td>
    <td></td>
</tr>
{%- endfor -%}

相关问题