Using Template Tags Django

26 February, 2016
Python Django

Over the last year, while i was working on my startup. I did coded a lot, multiple refactorings and more. As i kept doing it. There were things i wanted to clean up and make things more structured. At one point i stumbled on a situation where i need some logic while creating signature urls for authenticated access to my resources. After trying different things, using template tags is the best way to do this.

Sometimes it is very easy to ignore using these, but it makes your code a lot cleaner, easy to maintain and reusable

A simple template tag looks like

{% load url %}
{% url 'home' %}

Now you can create your custom tag which you pass objects and params as well. Let's say your app_name is dummy_app. Now create a python directory with templatetags which tells django that tags are defined and registered via this

Inside this directory, there is a __init__.py file and a another file let's say dummy_app.py

The content of dummy_app.py are as follows
from django import template
from django.contrib.contenttypes.models import ContentType
import random
register = template.Library()

@register.simple_tag(name="dummy_app_tag")
def post_comment_form_url(item, **kwargs):
    return_value ="dummy_value_%d"%random.randint(10)
    return return_value

The template dummy_app_tag takes in a compulsory param and returns a string "dummy_value_" with a random number integer appended to it. Now in your templates you can use this random css class names generator.

{% load dummy_app %}
{% dummy_app_tag item %} 
Thank you for taking the time to read this post. If you're considering using Digital Ocean, the hosting provider this blog is hosted on, please consider using this link to sign up.