Custom django templates tag

1. Inside an django app create an package templatetags :


2. Create a module inside the package.

We'll have a structure like this:

app/
    __init__.py
    models.py
    templatetags/
        __init__.py
        app_extras.py
    views.py

3. In the module put the following:

from django import template

register = template.Library() 
 

4. Create a function and register in library 

def function_name(value):

    value.replace('a', ' ')

5. Code example of the module app_extras.py

from django import template

register = template.Library() 

def function_name(value):

    value.replace('a', ' ')

register.filter('filter_name', function_name)

 

6. In the template we have to put the tag adding our custom template tag

{% load app_extras %}

 

7. Using our custom template tag.

{% variable|function_name %}

 

 

 

 

Comentarios