Django Tutorial: Making Your Own Template Filters
Django template tags and filters are huge time-savers and help you keep your presentation logic DRY and easy to maintain. Tags and filters are just small bits of code that allow you to perform formatting and simple presentation-related logic right in your template. Django filters are simple Python functions that accept a value, an optional argument, and return a value to be displayed on the page.
In this tutorial we will be creating a custom filter which will return the value of list at particular index.
You'll want this directory to be recognized as a Python package, so make sure you create an empty __init__.py file. Next, go ahead and create the Python file that will hold your tags and name it something like custom_filters.py or a similar name that is easily identifiable.
Here is what the folder structure should look like:
Django Project
-> my_app
---> models.py
---> views.py
---> templatetags
-----> __init__.py
-----> custom_filters.py
To get started, we'll need some imports at the top of our custom_filters.py file.
from django import template
from datetime import date, timedelta
register = template.Library()
register = template.Library() makes sure that your templates are added to the existing library of tags and filters that Django knows about. You can use the handy @register decorator and pass in the name of your filter to register it with Django.
@register.filter(name="value_at_index")
def value_at_index(list, index):
try:
return list[index]
except:
return -1
Then in the template where you want to use this template put {% load value_at_index %} at the top, then use as following:
{% for city in cities %}
...
<p> The name of city is {{ city }} and country is {{ countries|value_at_index:forloop.counter0 }}</p>
...
{% endfor %}
Where countries is also a list. In this way one can write a custom filter and one should be sure to handle all the exceptions that might occur.
No comments:
Post a Comment