2014-03-25 51 views
1

我开发一个应用程序语句的Python的Django 什么,我需要做的是一类分配到模板声明变量,如果在Django模板

{% 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 %} 

但我根据计数器变量值一个div面对这个问题

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

我在哪里提前犯错误,感谢您的帮助

+0

相反你自己开一个柜台,Django为你做这个。 –

+0

@digaph能否请你告诉我该怎么做,如果你能为我提供代码片段,我将不胜感激 –

回答

4

for循环设置了许多循环中可用的变量(完整列表,请Django文档here):

... 
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 %} 
+0

感谢您的回答,它肯定解决了我在这种情况下的问题,但因为我是新用户,我不能投票,我只需要选择正确的答案,请让我知道我的代码有什么问题意思是如何在Django模板中增加变量 –

+0

@AminBastani你不能自定义模板标签,因为我知道,检查这个例如:http://www.soyoucode.com/2011/set-variable-django-template – ndpu

1

问题是

{% counters += 1 %} 

没有标签counters。您正在将变量解释为标记。 你不能在django模板中实现那种for循环。

+0

正如你可以在这里阅读:https://docs.djangoproject.com/en/dev/ref/templates/ builtins /#与“旧”风格仍然支持 –

+0

@AlexanderMeesters,这与错误无关。 – Rohan

+0

OEPS,抱歉,确实没有,不知道我在想什么,现在重新阅读它,你确实是对的。也许我需要更多的咖啡:-)无论如何,我的歉意! –