views:

325

answers:

3

Hi

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.)

A: 

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.

Harper Shelby
But the question (unclear is it may be) was: how do I do the same thing without using a {% cycle %} in an HTML comment and without putting this into the view?
Deniz Dogan
+2  A: 

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 %} with as 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:

{% for day in days %}
  {% if forloop.counter|divisibleby:3 %}
     {% rounded "black" "day last" %}
  {% else %}
     {% rounded "black" "day" %}
  {% endif %}
{% endfor %}

but I don't think this is any better than what you have already.

Daniel Roseman
`{% cycle %}` with `as` *does* output it, something I normally wouldn't expect, but yeah... I'll go for your solution.
Deniz Dogan
A: 

Ummm...that's what the cycle tag is for. I have no idea why you're trying to avoid it, but you should know:

  1. Any logic requiring selective application of some rule will require python code, since template code doesn't assign to variables.
  2. The python code must be either called from a templatetag or view function logic.

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.

David Berger
The problem is that `{% cycle %}` is replaced with its result, which is why I had to resort to hiding the result with an HTML comment. A silly hack in other words which will shine through in the generated HTML source code. As Roseman pointed out, there was another way to accomplish the same thing.
Deniz Dogan