Issue
I am using bootstrap accordian element in a for loop in jinja template. The code is as follows:
<div class="accordion" id="accordionExample">
{% for article in articles %}
<div class="accordion-item">
<h2 class="accordion-header" id="{{article['Id']}}">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
{{article['Job Title']}}
</button>
</h2>
<div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
<div class="accordion-body">
{{article['Description']}}
</div>
</div>
</div>
{% endfor %}
When I am trying to open any one of the accordian-item, it is opening only the first item. Any way to rectify this? I already tried the approach in the question:
Using Jinja2 (flask) to loop through a bootstrap accordian
Bu it is not working. Data is formatted as below:
({'Id': 12941, 'Discipline': '0 Computational Science ', 'Job Title': 'High-performance Computing', 'Description': 'Some text here'})
EDIT: Basically articles are coming from flask backend and I need to render each of the article in a accordian type structure. I copied the code from the example 1 of the page: https://getbootstrap.com/docs/5.0/components/accordion/
Solution
<div class="accordion" id="accordionExample">
{% for article in articles %}
<div class="accordion-item">
<h2 class="accordion-header" id="Arr{{article['Id']}}">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#Arr{{article['Id']}}" aria-expanded="false" aria-controls="Arr{{article['Id']}}">
{{article['Job Title']}}
</button>
</h2>
<div id="Arr{{article['Id']}}" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
<div class="accordion-body">
{{article['Description']}}
</div>
</div>
</div>
{% endfor %}
The data-bs-toggle
should always be equal to the target accordion ID. So from my code above, {{article['Id']}}
would be the unique ID for Bootstrap to identify each accordion element.
Also from your code, the first seems to be the only opened because all .accordion-collapse
has same ID.
NOTE: The ID attribute should be unique in the whole of your page. No two elements should have same ID.
HTML ID on w3schools
EDIT: Added Arr
to the IDs, since numbers isn't a valid HTML ID.
Answered By - booluw
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.