[英]Flask/datatables.js - add buttons to table?
我想在表格中添加按钮,例如下图中的“编辑”和“删除”按钮。
我目前有这个:
server_table.py
@app.route('/')
def index():
return render_template('server_table.html', title='Recipes')
@app.route('/api/data')
def data():
query = Recipe.query
# search filter
search = request.args.get('search[value]')
if search:
query = query.filter(db.or_(
Recipe.name.like(f'%{search}%'),
Recipe.ingredients_str.like(f'%{search}%')
))
total_filtered = query.count()
# sorting
order = []
i = 0
while True:
col_index = request.args.get(f'order[{i}][column]')
if col_index is None:
break
col_name = request.args.get(f'columns[{col_index}][data]')
if col_name not in ['name', 'ingredients_str', 'cook_time']:
col_name = 'name'
descending = request.args.get(f'order[{i}][dir]') == 'desc'
col = getattr(Recipe, col_name)
if descending:
col = col.desc()
order.append(col)
i += 1
if order:
query = query.order_by(*order)
# pagination
start = request.args.get('start', type=int)
length = request.args.get('length', type=int)
query = query.offset(start).limit(length)
# response
return {
'data': [recipe.to_dict() for recipe in query],
'recordsFiltered': total_filtered,
'recordsTotal': Recipe.query.count(),
'draw': request.args.get('draw', type=int),
}
和 server_table.html:
{% extends "base.html" %}
{% block content %}
<table id="data" class="table table-striped">
<thead>
<tr>
<th>Recipe Name</th>
<th>Ingredients</th>
<th>Cook Time (Mins)</th>
<th> </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
{% endblock %}
{% block scripts %}
<script>
$(document).ready(function () {
$('#data').DataTable({
ajax: '/api/data',
serverSide: true,
columns: [
{data: 'name'},
{data: 'ingredients_str', orderable: false},
{data: 'cook_time', orderable: false}
],
});
});
</script>
{% endblock %}
我是 Flask 等的新手,所以我什至不知道从哪里开始。 这个网站上有几个类似的问题,但我找不到任何关于 Flask 的问题。 我的大部分代码都是从本教程中复制而来的。
一种可能性是这样做:
<script>
$(document).ready(function () {
$('#data').DataTable({
ajax: '/api/data',
serverSide: true,
columns: [
{data: 'name'},
{data: 'ingredients_str', orderable: false},
{data: 'cook_time', orderable: false},
{
"orderable": false,
"data": null,
"defaultContent": '<a class="btn btn-primary edit"> Edit </a>'+
'<br/>'+
'<a class="btn btn-danger delete"> Delete </a>'
},
],
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.