gevra
gevra

Reputation: 756

Reuse javascript function for bootstrap tables in Django

I want to create 4 identical in structure, but different in content bootstrap tables via javascript. The data for each table is in json format already.

I iterate over the list of table data jsons (each element in list is for one manufacturer) in the django template:

{% 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 %}

then I have a javascript function in the script block looking like this:

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
            }]
        });
});

As expected, this works only for one manufacturer only ("boeing" in this case). What can I do to modify and reuse this function for all the manufacturers?

Upvotes: 0

Views: 154

Answers (1)

Serafeim
Serafeim

Reputation: 15104

Just reuse the template logic to your javascript. Something like this if I've figured it out correctly:

$(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 %}
});

So the above will create N bootstrapTables with the correct id and data (through the for loop).

Upvotes: 1

Related Questions