Jinja模板中如何隔离不同Accordion的href避免交互冲突?
The core issue here is duplicate id attributes and corresponding data-bs-target values across your accordion panels. When multiple elements share the same ID, the browser will always target the first matching element in the DOM, which is why clicking dev's panel triggers qa's.
Solution: Generate Unique IDs Using Both Environment and Monitor Context
Create unique identifiers by combining the environment name and monitor item name in your Jinja template. This ensures every accordion panel and its trigger have distinct IDs that don't clash across environments.
Here's the corrected code example:
{% for env in ['dev', 'qa', 'prod'] %} <!-- Unique accordion container per environment --> <div class="accordion mt-3" id="accordion-{{ env }}"> {% for service in ['facebook', 'google'] %} <!-- Create a unique ID string for each panel --> {% set panel_id = env ~ '-' ~ service %} <div class="accordion-item"> <h2 class="accordion-header" id="heading-{{ panel_id }}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-{{ panel_id }}" aria-expanded="true" aria-controls="collapse-{{ panel_id }}"> {{ env | upper }} - {{ service | title }} Status </button> </h2> <div id="collapse-{{ panel_id }}" class="accordion-collapse collapse show" aria-labelledby="heading-{{ panel_id }}" data-bs-parent="#accordion-{{ env }}"> <div class="accordion-body"> <!-- Your status content here --> Real-time status for {{ service }} in {{ env }} environment </div> </div> </div> {% endfor %} </div> {% endfor %}
Key Changes Explained:
- Unique Panel IDs: The
panel_idvariable combinesenvandservice(e.g.,dev-facebook,qa-google), ensuring no two panels share the same ID. - Consistent Attribute Mapping: All related attributes (
data-bs-target,aria-controls,aria-labelledby) use this unique ID to link the trigger button to its correct panel. - Isolated Accordion Containers: Each environment's accordion has a unique
data-bs-parentvalue (#accordion-{{ env }}), which prevents panels from different environments interfering with each other's collapse state.
Why Swapping Loops Didn't Work
Swapping the order of your loops (services first, then environments) doesn't fix the problem because you're still not incorporating both context variables into the ID. You'd end up with duplicate IDs like dev-facebook and qa-facebook regardless of loop order—you need to explicitly combine both values to create uniqueness.
内容的提问来源于stack exchange,提问作者Fernandino Silva

