Visitor : 813

Read Comments

Custom Template Tag in Django template

Django Code Snippet


Custom Django template tag can be used to call Django view and operate on the variables passed from the template and return the value. This can be considered like a AJAX call when the back end view is called and value is returned.

Eg : Multiply 2 Tag values in the templateThere is no standard tag for this but ,using custom template the required activity can be achieved.

 

Steps

1. Create a new folder templatetags under the app folder in the same level as models.py

2. Create a new file for the template tag and define the function

3. Load the templatetag in the template before use

 

Django Documentation : https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/

Code layout

The most common place to specify custom template tags and filters is inside a Django app. If they relate to an existing app, it makes sense to bundle them there; otherwise, they can be added to a new app. When a Django app is added to INSTALLED_APPS, any tags it defines in the conventional location described below are automatically made available to load within templates.

The app should contain a templatetags directory, at the same level as models.pyviews.py, etc. If this doesn’t already exist, create it - don’t forget the __init__.py file to ensure the directory is treated as a Python package.

Development server won’t automatically restart

After adding the templatetags module, you will need to restart your server before you can use the tags or filters in templates.

Your custom tags and filters will live in a module inside the templatetags directory. The name of the module file is the name you’ll use to load the tags later, so be careful to pick a name that won’t clash with custom tags and filters in another app.

For example, if your custom tags/filters are in a file called poll_extras.py, your app layout might look like this:

polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py

In the template tag folder created for template tag use the following code as sample

Eg : Create template : multiply 

from django import template
register = template.Library()

@register.simple_tag()
def multiply(qty, unit_price, *args, **kwargs):
    # you would need to do any localization of the result here
    return qty * unit_price

 

In Template call the tag and pass values

 

{% load your_custom_template_tags %}

{% for cart_item in cart.cartitem_set.all %}
    {% multiply cart_item.quantity cart_item.unit_price %}
{% endfor %}

 




Add Comments