如何在Python Flask中为div标签的ID/类名添加循环变量值?
Hey there! Let's break down how to handle both of your template needs in Flask's Jinja2 engine—it's straightforward once you remember how Jinja2 handles variable interpolation.
Adding Loop Variables to div IDs
The syntax is identical to what you're testing for class names—just use Jinja2's {{ }} variable tags directly inside the id attribute. For example, if you want unique IDs tied to each loop iteration:
{% for i in range(5) %} <div id="item-{{ i }}"> <!-- Content for each item here --> </div> {% endfor %}
This will generate divs with IDs like item-0, item-1, up to item-4. If you prefer starting from 1 instead of 0, just adjust the variable to {{ i + 1 }}:
<div id="item-{{ i + 1 }}">
Adding Loop Variables to div Class Names
Your example code is almost perfect! The only thing to note is that range(5) in Jinja2 starts at 0, so your current code would generate classes cls0, cls1, cls2, cls3, cls4. If you want to start from cls1 as you mentioned (cls1, cls2, etc.), you'll need to add 1 to the loop variable:
{% for i in range(5) %} <div class="cls{{ i + 1 }}"> <!-- Content here --> </div> {% endfor %}
This will output exactly what you're expecting: divs with classes cls1, cls2, cls3, cls4, cls5.
A quick reminder: Jinja2 lets you interpolate variables anywhere in your HTML attributes—whether it's id, class, or even custom data attributes like data-index="{{ i }}"—the same {{ }} syntax applies.
内容的提问来源于stack exchange,提问作者qwww

