我正在使用Flask,我有一个从数据库中读取的数组,这个数组看起来像[[“customer”,“address”,“PPL”],[“customer2”,“address2”,“PPL2”]]
使用DataTables插件,我希望“customer”和“customer2”显示在customer列中,“address”和“address2”显示在address列中,“PPL”和“PPL2”显示在PPL列中。我可以在HTML中使用for循环来完成这项工作,但这会破坏数据表的格式,并从表中删除搜索框和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>

我被链接到这个帖子,How to structure data to easily build HTML tables in Flask
但如前所述,使用此for循环填充DataTables表中的列,但for循环似乎删除了搜索框和prev/next按钮。
Script.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' );

 } );

 } );

最佳答案

首先,在将数据发送到模板之前,不要使用json.dumps来转储数据。

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)

就用金贾的蟒蛇元组列表吧。
{%- for item in namesdb -%}
<tr>
    <td>{{ item[0] }}</td>
    <td>{{ item[1] }}</td>
    <td></td>
</tr>
{%- endfor -%}

关于python - 如何在数据表中显示Python数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53089605/

10-11 12:17
查看更多