When to use Templatetags in Django?

In today’s event loop on {{ PLP }}, we’ve another interesting discussion about how we can use the Django’s Templatetags and why is it an important piece of skillful techniques during the DOM manipulations in your template in Django.

The Django Context can’t handle most of the data manipulations before loading the Django template by itself, it needs a friend to massage your data further when the DOM has been loaded and it’s corresponding data that you wanted to be displayed in your template.

Django Context and Django Template tags are correlated and complement each other. This is how I wanted to demonstrate to you the importance of this technique to be implemented on your Django web projects.

This significant discussions for today will be beneficial and improve your skills as a Django web developer and answer the what-ifs in your heads on how we can achieve this technique based on my experience.

Just a glance at the rear, we have previous discussions about Securing NGINX using Let’s Encrypt on Ubuntu 18.04 that aims to secure our web server like the NGINX.

Introduction

The Django Templatetags is simply a Python function that you might need to execute in your template during the data manipulation or anything else that Python function might serve your application’s need.

I will guide you on how we can extend the Python function and called it from the HTML file in layman’s term which is called your Django template.

So, prepare your self once again and stay focus because this would be exciting and fun learning with {{ PLP }}.

Getting Started

The naming convention that Django uses inside your app folder name is the “templatetags” itself. No need to rename it nor change anything or put up some space in between because this is the exact folder name that Django uses it under the hood.

If you don’t have this folder name, please create it accordingly so we can start using the “templatetags” ability. Whatever we store inside this folder will all be a callable Python function and be loaded in our Django template.

Step 1: Create a “templatetags” folder.

As you can see from our GitHub repository at pinoylearnpython, we’ve created before the exact folder name but it’s an empty file, so we would like to use this “myroot_extras.py” during this demo. You can download this repo so you can follow along with me in this guide.

Make it sure that inside the folder “templatetags” must have the “__init__.py” Python file exist to make this folder treated as a Python package to be called anywhere from our application.

Step 2: Create your first custom callable Python Function inside the Django Templatetags.

In this case, open up your “myroot_extras.py” and make a mandatory import of the following Django built-in libraries to make a normal Python function to be called and executed from the template itself.

1
2
3
from django import template

register = template.Library()

The “register” variable is the standard name preserve to be used during a Python function registration to be treated as extendible and callable from a Django template.

Now, create a simple Python function, copy exactly the code snippets below.

1
2
3
4
5
6
7
8
@register.simple_tag
def split_me(strings):
    """
    Function to split strings into an array to loop later
    from the template.
    """

    splited_values = strings.split(",")
    return splited_values

Take a look at how we register the normal Python function as a Templatetag by using the “@register.simple_tag” decorator on top of it provided by the Django framework by itself. Now, this is a callable and ready to be called from the template.

We created a simple Python function with one single string parameter on it. With this function, we would like to just simply split any strings separated with “,” comma.

Step 3: How to load and use the Django Templatetag.

Now, the most awaited part of this guide is to use our custom Python function called the “split_me” that treated as a Django Templatetag in action from any template that you might need to be executed.

For now, we will re-use the existing template that we have earlier. Please open the “myroot/templates/myroot/cache_basic_crud_list.html” as a demo page for us to implement and showcase the power of the Django Templatetag.

1
2
3
...
{% load myroot_extras %}
...

Afterward, scroll on the very top of the lines, then insert the code above. This is how we load the Django Templatetag file that contains the “split_me” function. You can load many Templatetags from any templates as you want it, but, for now, we need only the “myroot_extras” to be loaded in this template.

Next, look for the “{{ d.full_name }}” field and modify this for us to implement the “split_me” Templatetag as an example.

1
2
3
4
...
{% split_me d.full_name as splited_full_name %}
<td>{{ d.full_name }} - {{ splited_full_name }}</td>
...

Have you noticed how we use the “split_me” function? the “{% split_me d.full_name as splited_full_name %}” is how to call the function.

After the “split_me” is where the required string parameter will be supplied, in this case, the “d.full_name” value from the Django Model returned from the Django Context before the template has been loaded.

Then “as” keyword is to assign the returned value to a variable, in this case, the “splited_full_name” is the variable name.

The “split_me” function returns an array, you can loop through with its value inside the template, but, for simplicity, we just have to display everything as the normal variable output.

You can also call the Django Templatetag, not in the template but also inside a normal Views in Django as well, you’ve just to import the Templatetags for example.

1
from myroot.templatetags.myroot_extras import split_me

And then, just use it as per normal function in Python and you can do anything with it from there like mystr = split_me(strvar) as simple as that.

Moreover, you can see it in the live demo for you to examine and see the implementation that we’ve just practice during this discussion.

https://dev.pinoylearnpython.com/cache-django-basic-crud-list/

You’ll notice that the full name column will have it’s split names when you create or modify the existing full name field. Try inserting value with comma-separated text so you will know how this function works.

So there we go young people, this is how we use the Django Templatetags and its importance in our Django web projects. It will be useful during the template manipulation and do some data massage. You can also use the Django Memcached as per normal to cache your Python function as per your requirement.

You can download the source code from our GitHub repositories at https://github.com/pinoylearnpython/dev and stay tuned for any updates.

In the next event loop on {{ PLP }}.

Congratulations! now you know when to use the Django Templatetags and how to trigger this inside your Django templates.

So, I expect your application will have this Django Templatetags be implemented with your new knowledge that you’ve gained today, don’t forget to share your newly gained knowledge to your school mates, friends or colleagues.

Please continue your practice using the Django Templatetags as I’ve created only one good but simple example for you to continue the practice.

For those who’re not able to successfully launch this discussion about When to use Templatetags in Django? a tutorial that I’ve laid it before you, or you need more clarifications, don’t worry, leave a comment below and I’m happy to help you to succeed.

That’s all, have fun learning with {{ PLP }}.

To help Filipino students to learn Python programming language with Django to enhance their capabilities in developing robust web-based applications with practical and direct to the point tutorials, step-by-step with actual information that I provided for you. Leave a comment below or email me at [email protected], thank you!