Create custom Template Tags in Django

  • By PyCat
  • Jun 03, 2016
  • Django Practices

Writing custom template tags

Django custom template tags can do anything. Django provides a number of shortcuts that make writing most types of tags easier. The most common place to specify custom template tags is inside you Django app. The app should contain a templatetags  directory (at the same level as models.py, views.py etc). If it does'nt already exists you can create it manual.

Your app layout should look like this:


appname/
    __init__.py
    models.py
    views.py
    templatetags/
         __init__.py
         my_tags.py

 

*Don’t forget the __init__.py file to ensure the directory is treated as a Python package.

 

In the example above we 're going to write an inclusion_tag

This type is a common type o template tags that displays some data by rendering another template. In the example above we will write an inclusion_tag that helps us to render one part of the main menu within the base template.

 

We are going to use the inclusion_tag library:

django.template.Library.inclusion_tag

 

Then we can write our script within the my_tags.py file. The code looks like this:


from django import template
from portfolio.models import Page

register = template.Library()

@register.inclusion_tag('page/pages_menu.html')

Now let's explain the above code line by line


from django import template
register = template.Library()

 

To be a valid tag library, our script must contain a module-leve variable named register, an instance o the template.Library in witch all tags and filters are register in Django.


from portfolio.models import Page

Now this one is simple to explain. In this example we need to display data from the Page model so we need to import the Page model


@register.inclusion_tag('page/pages_menu.html')

Next we need to register the tamplate and at the end of our script comes our function, in this example our function is typical to a view.py function.


def show_pages_menu(pages_menu):
    pages_menu = Page.objects.all()
    return { 'pages_menu' : pages_menu }

At this point we'we just finished with the banckend an all we need is to show the results in our template:

{% show_pages_menu pages_menu %}

 

This was just an example of using Custom Teamplate Tags in Django, you can visit Django's Documentaion page to find out more variations of using  template tags. 


Sources: Django Project

Comments

======= >>>>>>> master

+30 211 790 2526

Find me

kabardi.cat@gmail.com