Reputation: 149
I am new to the Django template language and I am playing around with bootstrap collapses to display my items. Below is my code:
{% for item in items %}
<div id="accordion">
<div class="card">
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
{{item.item_name}}
</button>
</h5>
</div>
<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
<div class="card-body">
{{item.description}}
</div>
</div>
</div>
</div>
{% endfor %}
This is taken from the Bootstrap documentation for collapse, here. In this implementation, all of the items passed in would have the same id, collapseOne. So whenever I click on an item, any item, it would collapse/uncollapse every item on the page. I've tried id="collapse{{item.item_name}}"
but that doesn't seem to work. Is there a way to pass in variables in <div> id?
Upvotes: 1
Views: 1134
Reputation: 5854
try this
{% for item in items %}
<div id="accordion">
<div class="card">
<div class="card-header" id="heading{{forloop.counter}}">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse{{forloop.counter}}" aria-expanded="true" aria-controls="collapse{{forloop.counter}}">
{{item.item_name}}
</button>
</h5>
</div>
<div id="collapse{{forloop.counter}}" class="collapse show" aria-labelledby="heading{{forloop.counter}}" data-parent="#accordion">
<div class="card-body">
{{item.description}}
</div>
</div>
</div>
</div>
{% endfor %}
https://docs.djangoproject.com/en/3.1/topics/templates/#the-django-template-language
Upvotes: 2