Django: Template Tags and Filters

Template is the one of powerful features of Django Framework, and we will discuss the tag and filter. If you do not have any idea about the template, please go read about that here, I will wait for you.

Template tags which we are going to discuss today are

URL The URL tag is the template equivalent of the reverse function. URL can accept args or kwargs for routes that expect other variables.

<a href="{% url "a_named_view" %}">Go to a named view</a>

Now Now is a convenient method to display information about the current time. It was a problem solver for the copyright year update, which I first have to update every year manually.

&copy; {% now "Y" %}

Spaceless It removes the whitespace, newline, tab from the HTML

{% spaceless %}
        <span>I am a good span.</span>
{% endspaceless %}

Now let's talk about the filter which we can use in the template.

Date This filter can be used to control the format of the datetime passed in the context of the response.

{{ birth_date|date:"Y-m-d" }}

Default Have you ever been in a condition when you want to show a text for a falsy value, then default filter is the one thing you should use

{{ value_to_check|default:"Nothing to see here." }}

Pluralize When your text considers counts of things. Pluralize can use to save you from if and else check

{ count_items }} item{{ count_items|pluralize }}

0 items
1 item
2 items
3 items
(and so on)

YesNo YesNo is good for converting True|False|None into a meaningful text message

{{ }} has {{ user_accepted|yesno:"accepted,declined,not RSVPed" }} request.

These are the tags and filter which I use very often but there many more which you can check out here


#100DaysToOffload #Python #Django