Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top