jma
jma

Reputation: 3779

django list view with first and last special

I am displaying a list view in a django template, I'd like to have the first and last elements displayed use different CSS classes than the interior elements.

I can do this by taking a slice on the python side and passing in list_of_things (the slice, which omits the first and last elements), first_in_list, and last_in_list. I can do the same on the template side with {% list_of_elements|slice %}, {% list_of_elements|first %}, {% list_of_elements|last %}. But both seem inelegant, since they require me to repeat the html line three times (for interior, first, and last).

What I'd like is a template-side test so that I can {% if ... %} for just the parts that change. Does this exist? Or is there a better way?

Thanks.

Upvotes: 1

Views: 897

Answers (2)

Ska
Ska

Reputation: 6888

You could also use just CSS for that, no Django or template code.

Table example

tr:nth-last-child(1) { ⋮ declarations }

List example

li:first-child { ⋮ declarations }

etc...

Upvotes: 0

jro
jro

Reputation: 9474

You could inline your if-statements:

<ul>
  {% for e in list_of_elements %}
    <li class='{% if forloop.first %}first{% endif %}{% if forloop.last %}last{% endif %}'>{{ e }}</li>
  {% endfor %}
</ul>

Edit: line breaks for readability:

<ul>
  {% for e in list_of_elements %}
    <li class='{% if forloop.first %}first{% endif %}
               {% if forloop.last %}last{% endif %}'>
      {{ e }}
    </li>
  {% endfor %}
</ul>

Upvotes: 4

Related Questions