为Django中的引导表重用javascript函数

Reuse javascript function for bootstrap tables in Django

本文关键字:javascript 函数 Django      更新时间:2023-09-26

我想通过javascript创建4个结构相同但内容不同的引导表。每个表的数据已经是json格式了。

我迭代django模板中的表数据jsons列表(列表中的每个元素都代表一个制造商):

{% for helis in helis_by_mnfcr %}
    {% if helis %}
       <table id="table_{{ helis.0.mnfcr.split|join:"_" }}" data-sort-name="score" data-sort-order="desc">
       </table>
    {% endif %}
{% endfor %}

然后我在script块中有一个javascript函数,看起来像这样:

data_boeing = {{ helis_by_mnfcr.0|safe }}
$(function () {
    $(#table_boeing).bootstrapTable({
        data: data_boeing,
        striped: true,
        pagination: true,
        pageSize: 4,
        pageList: [4, 10, 25],
        search: true,
        showColumns: true,
        showRefresh: true,
        minimumCountColumns: 2,
        clickToSelect: true,
        columns: [
            {
                field: 'name',
                title: 'Name',
                valign: 'middle',
                width: '75%',
                formatter: NameFormatter,
                events: operateEvents
            }, {
                field: 't',
                title: 'Deployed',
                align: 'center',
                valign: 'middle',
                width: '15%',
                sortable: true
            }]
        });
});

正如预期的那样,这只适用于一家制造商(在这种情况下为"波音")。我可以做些什么来为所有制造商修改和重用此功能?

只需将模板逻辑重用到javascript即可。如果我没记错的话是这样的:

$(function () {
  {% for helis in helis_by_mnfcr %}
    {% if helis %}
      {% with id=helis_by_mnfcr.mnfcr.split|join:"_" %}
      var table_id = '#table_{{ id }}';
        $(table_id).bootstrapTable({
          data: data_{{ id }},
          striped: true,
          pagination: true,
          // ... Other attrs ommited
        });
      {% endwith %}
    {% endif %}
  {% endfor %}
});

因此,上面将创建具有正确id和数据的N引导表(通过for循环)。