I want to write a template which
li-tag contains an a-tag that is linked to a model.) That means the list not alway starts with 1.My model:
class Mymodel(models.Model):
number = positiveIntegerField()
title = models.CharField(max_length=100)
[...]
number is unique, ordered and when you order the models with the number, there is no gap; number is 1-based
What I have: (reverse is boolean variable which tells whether the list has to be reversed or not)
{% if reverse %}
<ol class="content" start="{{ article_list.0.number|add:article_list.count }}" reversed=true>
{% for article in article_list reversed %}
<li class="{% cycle '' '' '' '' 'seperate-bot border-gray' %}"><a href="{% url 'myapp:article' article.number %}">{{ article.title }}</a></li>
{% endfor %}
{% else %}
<ol class="content" start="{{ article_list.0.number }}">
{% for article in article_list %}
<li class="{% cycle '' '' '' '' 'seperate-bot border-gray' %}"><a href="{% url 'manifest:article' article.number %}">{{ article.alt_title }}</a></li>
{% endfor %}
{% endif %}
</ol>
Unfortunately counts the backward template part wrong: the last number is always 1 which it shouldn't be. The last number should be article_list.0.number + article_list.count (or: article_list|length) -1; or last_list_item.number that would be better.
That means: (paginated_by = 3 for that example) the "|" because SO changes my counting How it should be: (reverse=true)
page 1:
|3. lorem ipsum
|2. lorem ipsum
|1. lorem ipsum
page 2:
|5. lorem ipsum
|4. lorem ipsum
What I get: (only page 2 is bad)
page 2:
|2. lorem ipsum
|1. lorem ipsum
Is there a good way to avoid that effect? (And where does it come from?) In the best case that should work in the template only.
I'm not sure why you would get that result, but this seems like a overly complicated way to do something quite straightforward.
You can use the built in last filter and with template tag to access the last item in a list.
{% with article_list|last as last_article %}
<ol class="content" start="{{ last_article.number }}" reversed=true>
{% endwith %}
However, I would recommend you do the ordering and reversing in the view function instead of in the template. Django's template language is by choice not suited for non trivial logic.
As for the numbering, you can actually explicitly assign a value attribute to a ordered list element. This would solve your problem.
<li value={{ article.number }} ...
Example:
<ol>
<li value=3>it doesn't
<li>have to
<li>make
<li value=42>sense
</ol>