<div id="{{ component.template_id }}">
  <table id="{{ component.template_id }}_table" class="{{ component.css_classes.table }}" style="width:100%"></table>
</div>

{% with data_key="data_"|add:component.template_id columns_key="columns_"|add:component.template_id order_key="order_"|add:component.template_id%}
  {% if not component.is_deferred %}
    {{ rendered_value|json_script:data_key }}
  {% endif %}
  {{ rendered_value.columns_datatables|json_script:columns_key }}
  {{ rendered_value.order|json_script:order_key }}
  <script type="module">
      var columns_{{ component.template_id }} = JSON.parse(document.getElementById('{{ columns_key }}').textContent);
      var order_{{ component.template_id }} = JSON.parse(document.getElementById('{{ order_key }}').textContent);

      {% if not component.is_deferred %}
          let data_{{ component.template_id }} = JSON.parse(document.getElementById('{{ data_key }}').textContent);
          let rows_{{ component.template_id }} = data_{{ component.template_id }}.data;

          var options = {
              data: rows_{{ component.template_id }},
              columns: columns_{{ component.template_id }},
              pageLength: {{ component.page_size|default:25 }},
              scrollX: true,
              searching: {{ component.searching|yesno:"true,false" }},
              paging: {{ component.paging|yesno:"true,false" }},
              info: {{ component.paging|yesno:"true,false" }},
              ordering: {{ component.ordering|yesno:"true,false" }},
              order: order_{{ component.template_id }},
          }

      {% else %}
          $.ajaxSetup({
             headers: { "X-CSRFToken": JSON.parse(document.body.getAttribute("hx-headers"))["X-CSRFToken"]}
          });
          var options = {
              destroy: true,
              scrollX: true,
              processing: true,
              serverSide: true,
              searching: {{ component.searching|yesno:"true,false" }},
              paging: {{ component.paging|yesno:"true,false" }},
              info: {{ component.paging|yesno:"true,false" }},
              ordering: {{ component.ordering|yesno:"true,false" }},
              columns: columns_{{ component.template_id }},
              pageLength: {{ component.page_size|default:25 }},
              order: order_{{ component.template_id }},
              ajax: {
                  url: "{{ component.get_absolute_url }}",
                  type: "POST",
                  dataFilter: function(data){
                    let json = jQuery.parseJSON( data );
                    json.recordsTotal = json.total;
                    json.recordsFiltered = json.filtered;
                    return JSON.stringify( json );
                }
              }
          }
      {% endif %}

      var table_{{ component.template_id }} = $('#{{ component.template_id }}_table').DataTable(options);
  </script>
{% endwith %}


