You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Flask中为div标签的ID/类名添加循环变量值?

Flask Jinja2: Adding Loop Variables to div IDs and Class Names

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:03:04