Django:{%循环%}有问题
这直接取自我的 Django 模板:
{% for day in days %}
<!-- {% cycle 'day' 'day' 'day last' as cls %} -->
{% rounded "black" cls %} {# Custom tag giving me rounded borders. #}
...
{% endrounded %}
{% endfor %}
我注释掉了 {% Cycle %}
因为我只用它来将“cls
”设置为“day last”
”循环中每第三次迭代。有没有更好的方法可以在不向视图添加任何代码的情况下执行此操作? (人们说逻辑应该远离模板,但反之则更糟糕。)
This is taken directly from my Django template:
{% for day in days %}
<!-- {% cycle 'day' 'day' 'day last' as cls %} -->
{% rounded "black" cls %} {# Custom tag giving me rounded borders. #}
...
{% endrounded %}
{% endfor %}
I have commented out the {% cycle %}
because I only use it to set "cls
" to "day last
" every third iteration in the loop. Is there any better way to do this without adding any code to the view? (People say that logic should stay out of templates, but having it the other way around is almost worse.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定我是否理解您遇到问题的原因,因为您当前的解决方案似乎有效。我认为您不需要 HTML 注释,因为
{% Cycle %}
和as
不会输出任何内容,但除此之外它似乎还不错。但是,如果您想要另一种方法来做到这一点,您可以使用
divisibleby
过滤器:但我认为这并不比您已有的更好。
I'm not sure I understand why you have a problem, since your current solution seems to work. I don't think you need the HTML comments, since
{% cycle %}
withas
doesn't output anything, but apart from that it seems fine.However if you want another way to do it, you could use the
divisibleby
filter:but I don't think this is any better than what you have already.
“Django 开发版本中的新增功能”
循环“as”标签现在具有“静默”模式:
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#cycle
http://code.djangoproject.com/ticket/13567
'New in Django Development version'
The cycle 'as' tag now has a 'silent' mode:
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#cycle
http://code.djangoproject.com/ticket/13567
应用程序逻辑不应该位于您的模板中。表示逻辑确实属于那里(看起来就是这样)。我会把它放在那里。
Application logic shouldn't be in your templates. Presentation logic does belong there (which is what this appears to be). I'd put it there.
嗯...这就是
cycle
标签的用途。我不知道你为什么要试图避免它,但你应该知道:因此,如果您不使用视图逻辑,那么您就会陷入模板标签的困境。要么你自己编写,要么使用内置的。
cycle
似乎和其他任何东西一样简单。有什么问题。Ummm...that's what the
cycle
tag is for. I have no idea why you're trying to avoid it, but you should know:So if you won't use view logic, you're stuck with a templatetags. Either you write your own or you use one that's built in.
cycle
seems to be about as easy as any other. What's the problem.