【问题标题】:generate unique id in each loop of for loop django template在 for loop django 模板的每个循环中生成唯一的 id
【发布时间】:2020-06-21 12:40:37
【问题描述】:

我需要在每个循环中生成唯一的 id 而不是 ````city-selected```

{% for form in formset.forms %}
    <tr>
        {% for field in form %}
            <td class="input_td{% if field.errors %} error_td{% endif %}">
                <select name="city-select" id="city-select"></select>
            </td>
        {% endfor %}
        <td class="delete_formset_td"></td>
    </tr>
{% endfor %}

如何在此处生成?

我需要一些类似的东西用于 ids:

输出

city-1
city-2
city-3
...

【问题讨论】:

  • 这能回答你的问题吗? How to generate random numbers in django
  • 不,首先我需要它在前端的 django-template 中。其次,我需要city-select-i 之类的东西,但我不知道应该如何生成该ID 并在nameid 部分中使用它。 @AnuragSrivastava
  • 这能回答你的问题吗? Django template counter in nested loops看第二个答案。
  • 如何在 id 部分使用生成的文本? @IvanStarostin
  • id="city-select-{{ variable }}"

标签: html django django-templates frontend


【解决方案1】:

您可以使用{{ forloop.counter }}。它以数字形式为您提供循环迭代。

here

{% for field in form %}

    <!-- your html -->

    city-{{ forloop.counter }}

{% endfor %}

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2012-09-22
    • 2021-10-17
    相关资源
    最近更新 更多