Activate the first Bootstrap collapse in Django for dynamic data.
Sadiqul Islam
Posted on March 4, 2023
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:
- 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 %}
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.
- 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');
});
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.
Posted on March 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
May 18, 2022