如何在模板Django中增加变量

时间:2019-01-14 10:49:39

标签: django django-templates django-views

这是我的delcared函数所在的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行上的无效块标记:“设置”,预期为“结尾为”。你是否   忘记注册或加载此标签?

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

1 个答案:

答案 0 :(得分:3)

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