使用Jinja2来确定循环中的div ID?

Chr*_*son 1 python jinja2 flask

我似乎找不到解决此问题的方法。

我有一个模板,可以从数据库中的几个不同表中获取输入。这些表包含x信息量。为了只显示一些onClick信息,我使用了一些JavaScript来隐藏它所包含的div。但是,在jinja的forloop期间填充的div id = {{row.id}}。我以为一开始效果不错,直到我意识到{{row.id}}可以与不同的{{row.id}}相同(如果它来自不同的表)。

{% 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>
Run Code Online (Sandbox Code Playgroud)

所以我遇到的问题是row.id == entry.id可能是因为它们来自不同的表。我试图弄清楚是否可以使用带有随机唯一数字的大型列表来绘制div ID的来源?我不知道如何让神社来做到这一点?我在这里只是运气不好吗?这是此模板中的最后一个主要障碍,因此我很想找出一些解决方案。

bru*_*ers 6

您为什么不在html ids前面加上表名呢?

{% 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>
Run Code Online (Sandbox Code Playgroud)