Passing Django variable to an accordion attribute in HTML
I am newbie to Django and apologize in advance for such a basic question to most of you, but I looked for similar questions all over and haven't encountered a workable solution.
I am trying to create a Bootstrap Accordion for each item of a Django for-loop. So a list of items is displayed, and when you click on one item, the description of it will collapse to show. The segment currently looks like this using this template:
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
{% for item in items %}
<div class="accordion" id="accordionExample">
<div class="accordion-item">
<h2 class="accordion-header" id="headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-parent="#accordion" data-bs-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
{{ item }}
</button>
</h2>
<div id="collapseOne" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
<div class="accordion-body">
{{ item.description }}
</div>
</div>
</div>
</div>
</body>
Now, this is giving the same value (collapseOne
) to data-bs-toggle
, aria-controls
and id
of accordion-collapse
class(collapsing element) for every for-loop item, resulting in all the accordion items collapsing when one of them is clicked though I want only the clicked one to collapse.
So I tried to pass the Django variable as such:
{{ item }}
in place ofcollapseOne
{{ forloop.counter }}
in place ofcollapseOne
The accordion still shows, but it doesn't collapse when clicked.
Is there a way to pass a Django variable to attributes of accordion-item? Or any other work around?
I'd appreciate your advice.
You should be able to use the {{ forloop.counter }}
- just make sure to update the value everywhere you need:
{% for item in items %}
<div class="accordion" id="accordionExample">
<div class="accordion-item">
<h2 class="accordion-header" id="heading-{{ forloop.counter }}">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-parent="#accordion" data-bs-target="#collapse-{{ forloop.counter }}" aria-expanded="false" aria-controls="collapse-{{ forloop.counter }}">
{{ item }}
</button>
</h2>
<div id="collapse-{{ forloop.counter }}" class="accordion-collapse collapse" aria-labelledby="heading-{{ forloop.counter }}" data-bs-parent="#accordionExample">
<div class="accordion-body">
{{ item.description }}
</div>
</div>
</div>
</div>
{% endfor %}