[Django] Template Tag/Filter (Loop/Datetime)
Make the First Element of a Django Template Loop Different from Others
The method of adding and removing current class with JavaScript to give different styling and action needs an extra step with django. When elements are created with loops, adding current class to one of the elements will automatically copy them into all others, unless there is a way to set the first item of the loop.
{% for post in posts_list %}
{% if forloop.first %}
<div class="preview current">
{% else %}
<div class="preview">
{% endif %}
{% endfor %}
Jinja loop.index does not print
Point here is that although django template tag uses the Jinja syntax, in this case keyword to access to elements of loop is django specific forloop
Additionally, due to the same mechanism as above, it would be wise not to use the id attribute with html, since this could create several elements with the same id, which could cause various errors. Use classes instead.
Django Template’s Datetime
Django has a built-in datetime template tag. The tag for calling current time is {% now %}
. Various formats could be added to this time by adding filters such as {% now "Y" %}
for years. Other filters are in the link below.
Built-in template tags and filters | Django documentation | Django