Alternate Row Coloring in Django Template with More Than One Set of Rows

前端 未结 7 1148
广开言路
广开言路 2020-12-07 14:37

Django templates offer the builtin tag cycle for alternating between several values at different points in a template (or for loop in a template) but this tag d

相关标签:
7条回答
  • 2020-12-07 15:05

    There's a way to do it server-side with an iterator that doesn't keep a simultaneous copy of all the entries:

    import itertools
    return render_to_response('template.html',
      {
        "flattened_entries": itertools.chain(*(blog.entries for blog in blogs)),
      })
    
    0 讨论(0)
  • 2020-12-07 15:09

    The easiest answer might be: "give up and use jQuery." If that's acceptable it's probably easier than fighting with Django's templates over something so simple.

    0 讨论(0)
  • 2020-12-07 15:12

    The easiest workaround (until the resetcycle patch gets fixed up and applied) is to use the built-in "divisibleby" filter with forloop.counter:

    {% for entry in blog.entries %}
      <div class="{% if forloop.counter|divisibleby:2 %}even{% else %}odd{% endif %}" id="{{ entry.id }}">
        {{ entry.text }}
      </div>
    {% endfor %}
    

    A little more verbose, but not hard to understand and it works great.

    0 讨论(0)
  • 2020-12-07 15:13

    You can use tagged cycle and resetcycle (new in Django 1.11) calls (from https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#std:templatetag-resetcycle ):

    {% for blog in blogs %}
      {% cycle 'odd' 'even' as rowcolors silent %}
      {% resetcycle rowcolors %}
      {% for entry in blog.entries %}
        {% cycle rowcolors %}
        <div class="{{ rowcolors }}" id="{{entry.id}}">
          {{ entry.text }}
        </div>
      {% endfor %}
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-07 15:18

    I end up doing so, with the forloop.counter0 - It works great!

    {% for product in products %}
    
        {% if forloop.counter0|divisibleby:4 %}<div class="clear"></div>{% endif %}
    
        <div class="product {% if forloop.counter0|divisibleby:4 %}col{% else %}col20{% endif    %}">
            Lorem Ipsum is simply dummy text
        </div>
    
    {% endfor %}
    
    0 讨论(0)
  • 2020-12-07 15:30

    https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#cycle

    {% for o in some_list %}
        <tr class="{% cycle 'row1' 'row2' %}">
            ...
        </tr>
    {% endfor %}
    
    0 讨论(0)
提交回复
热议问题