【问题标题】:How to increment a variable in a template Django如何在模板Django中增加变量
【发布时间】:2019-06-08 08:30:12
【问题描述】:

这是我的 views.py 文件,我在其中设置了函数

副标题

加载帐户对象以查看

def subhead(request):
    subheads=Account.objects.all()

    return render(request,'my/test.html',{'accounts':subheads})

这是我的模板

{% for subhead in subheads %}
         {% with i=0  %}
           {% if subhead.parent == None and subhead.type == 'As' %}
              {% if i == 0 %}

                  <tr>
                    <td>Assets</td>
                      <td>{{ subhead.name }}</td>
                  </tr>
               {% else %}
                 <tr>
                   <td></td>
                   <td>{{ subhead.name }}</td>
                 </tr>

               {% endif %}
             {% endif %}
          {% set i=i+1  %}
        {% endwith %}
{% endfor %}

现在我只是想增加一个变量值但我不知道如何实现这个任务。我已经定义了一个变量 i =0 并尝试设置它的值。但它返回一个错误

第 419 行的块标记无效:'set',预期为 'endwith'。你是否 忘记注册或加载此标签?

而forloop.counter不适合case。因为我想计算if条件并且想显示一次静态td。所以请不要建议它

【问题讨论】:

  • 你需要解释为什么 forloop.counter 不是你想要的。
  • 你真的在找forloop.counter0吗?
  • 因为我想计算 if 条件并且想显示静态 td 一次。所以这与forloop.counter无关。 @丹尼尔罗斯曼

标签: django django-templates django-views


【解决方案1】:

在 for 循环中,Django 本身已经填充了一些特殊的 template variables。对于您的示例,您可以检查{% if forloop.counter == 1 %}{% if forloop.first %}

【讨论】:

  • 对不起伙计,但我不想使用 forloop.counter 。
猜你喜欢
  • 1970-01-01
  • 2011-01-31
  • 2019-08-07
  • 2012-01-29
  • 2011-11-05
  • 2014-09-14
  • 1970-01-01
  • 2020-06-02
  • 1970-01-01
相关资源
最近更新 更多