在for循环中枚举带有标记ol的元素

时间:2018-05-16 02:10:59

标签: django

我希望枚举for循环中的元素,标记为' ol'代码:

{% for topic in topics  %}
    <ol>
        <li>{{ topic }}</li>
    </ul>

{% endfor %}

显示

 1.Python
 1.Javascript
 1.SQL

尝试时:

{% for topic in topics  %}
    <ol>
        <li>{{ forloop.counter }}{{ topic }}</li>
    </ol>

{% endfor %}

输出:

 1.1.Python
 1.2.Javascript
 1.3.SQL

将代码重构为并运行:

{% for topic in topics  %}
    <ul>
        <li>{{ forloop.counter }}. {{ topic }}</li>
    </ul>

{% endfor %}

解决方案看起来很麻烦,难道能够以直接的方式实现吗?

1 个答案:

答案 0 :(得分:3)

您只需在<ol>之外移动forloop标记声明即可 防止在每次迭代时创建新列表:

<ol>
{% for topic in topics  %}
    <li>{{ topic }}</li>
{% endfor %}
</ol>

注意:删除{{forloop.counter}}