在Django模板中声明变量和if语句

2 投票
2 回答
3049 浏览
提问于 2025-04-17 23:47

我正在用Python的Django框架开发一个应用程序。我的需求是根据模板中计数器变量的值给一个div(网页中的一个区域)分配一个类。

  {% with 1 as counters %}  
     {% for importance in all_importance %}

            {% if counters == 1 %}
                <div class="item active" >
            {% else %}
                <div class="item" >         
            {% endif %} 
            {% for image in importance.subtypemodelimage_set.all %}
                <img src="{{ image.image.url }}" />
            {% endfor %}

        </div>
        {% counters += 1 %} 
     {% endfor %}
  {% endwith %}

但是我遇到了这个问题。

  Invalid block tag: 'counters', expected 'empty' or 'endfor'

我哪里出错了呢?谢谢大家的帮助!

2 个回答

1

问题出在

{% counters += 1 %}

这里没有 counters 这个标签。你把变量当成标签来理解了。而且,你不能在 Django 模板中使用那种 for 循环。

5

for循环会在循环内部设置一些变量(完整的列表可以在django文档中找到,这里):

...
forloop.first   True if this is the first time through the loop
forloop.last    True if this is the last time through the loop
...

你可以使用 forloop.first 来检查是否是第一次循环:

{% for importance in all_importance %}

    {% if forloop.first %}
        <div class="item active" >
    {% else %}
        <div class="item" >         
    {% endif %} 

    {% for image in importance.subtypemodelimage_set.all %}
        <img src="{{ image.image.url }}" />
    {% endfor %}

        </div>

 {% endfor %}

撰写回答