Translate

Friday 16 May 2014

Django template filter

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.

First of all, you'll want to create a directory for holding your custom template filters. This is a requirement: custom template filters must live inside a Django app. Note that if you plan on building a small library of custom tags or filters, to be used across an entire project, you could create a Django app just for holding these files. If not, keep it simple: each app gets a templatetags directory at the same level as the models and views.
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