Christopher Nelson Christopher Nelson - 1 month ago 9
Python Question

Using Jinja2 for unqiue div ID's during loop?

I can't seem to figure out a way around this issue..

I have a template that takes inputs from a few different tables in a database. Those tables contain x amount of info. In order to only show some info onClick i'm using a bit of javascript to hide the div that it is contained in. However, that div id={{ row.id }} that gets populated during the forloop in jinja. I thought it was working well at first until I realized that {{ row.id }} can be the same as a different {{ row.id }} if it is coming from a different table.. exmaple;

{% for row in packages %} # Packages is one of the tables
<div id="{{ row.id }}">
{{ row.price }}
{{ row.date }}
..etc
</div>
<button onClick="toggleDiv("{{ row.id }}">Show Content</button>

other stuff in between...

{% for entry in services %} # Services is one of the tables
<div id="{{ entry.id }}"> # is it possible to do something like entry.id + {{ loop.index }} ? I'm not positive that would make it unique tho.
{{ entry.price }}
{{ entry.date }}
..etc
</div>
<button onClick="toggleDiv("{{ entry.id }}">Show Content</button>


So the issue I am running into is that it is possible for row.id == entry.id because they come from different tables. I was trying to figure out if maybe I can use a large list with random unique numbers to draw the div id's from? I'm not sure how I can get jinja to accomplish that? Am I just out of luck here? This is the last major hurdle in this template so I would love to figure out some solution.. Any thoughts?

Answer

Why don't you just prefix the html ids with the table name ?

{% for row in packages %} # Packages is one of the tables
<div id="package_{{ row.id }}">
{{ row.price }}
{{ row.date }}
..etc
</div>
<button onClick="toggleDiv("package_{{ row.id }}")">Show Content</button>


{% for entry in services %} # Services is one of the tables
<div id="service_{{ entry.id }}"> 
{{ entry.price }}
{{ entry.date }}
..etc
</div>
<button onClick="toggleDiv("service_{{ entry.id }}")">Show Content</button>