DEV Community

Sadiqul Islam
Sadiqul Islam

Posted on

Activate the first Bootstrap collapse in Django for dynamic data.

To activate the first Bootstrap collapse in Django for dynamic data, you can use a combination of Django template tags and JavaScript. Here's how you can do it:

  1. In your Django template, use a loop to iterate over your dynamic data and generate the necessary HTML elements for the collapsible sections. Make sure to give each collapsible section a unique ID.
{% for item in dynamic_data %}
  <div class="card">
    <div class="card-header" id="heading{{ forloop.counter }}">
      <h2 class="mb-0">
        <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse{{ forloop.counter }}" aria-expanded="{% if forloop.first %}true{% else %}false{% endif %}" aria-controls="collapse{{ forloop.counter }}">
          {{ item.title }}
        </button>
      </h2>
    </div>
    <div id="collapse{{ forloop.counter }}" class="collapse {% if forloop.first %}show{% endif %}" aria-labelledby="heading{{ forloop.counter }}" data-parent="#accordion">
      <div class="card-body">
        {{ item.content }}
      </div>
    </div>
  </div>
{% endfor %}

Enter fullscreen mode Exit fullscreen mode

In this example, we're using Bootstrap's card and collapse components to create the collapsible sections. We're also using Django's for loop and forloop.counter to generate unique IDs for each section. Note that we're setting aria-expanded to true for the first section and false for the rest.

  1. Add the necessary JavaScript code to activate the first collapsible section. You can do this by using jQuery to trigger a click event on the first collapsible section's button.
$(document).ready(function() {
  // Trigger click event on first collapsible section
  $('#heading1 button').trigger('click');
});

Enter fullscreen mode Exit fullscreen mode

In this example, we're using jQuery's ready() function to wait for the page to load before triggering the click event. We're then using jQuery's trigger() function to simulate a click on the button of the first collapsible section.

Note that in this example, we're assuming that the first collapsible section has an ID of heading1. If your IDs are different, you'll need to adjust the JavaScript code accordingly.

By using this approach, the first collapsible section will be automatically expanded when the page loads, while the rest will be collapsed.

Top comments (0)