Django: Quick and easy template tags

0 Comments

Compared to Drupal, Django makes it incredibly easy to create new template tags. All you have to do is create the template tag file, a template file to populate and start using it.

First, create the template tag file "whatever.py" in your "project/app/templatetags" folder. This contains the template tag(s) which you want to make available to your templates.

The file should contain a template tag declaration similar to the following:

01.from django.conf import settings
02.from django.template import Library
03. 
04.register = Library()
05. 
06.@register.inclusion_tag('app/list_of_stuff.html', takes_context = True)
07.def app_list_of_stuff(context, arg):
08.    user = context['user']
09.    return { 'user': user, 'arg': arg, 'plus': arg + 10 }

Now create a template which renders the data returned by the template tag. In either "project/app/templates/app" or "project/templates/app", create a file called "list_of_stuff.html".

With it, paste in the following:

1.<ul class="list_of_stuff">
2.  <li>{{user.id}}</li>
3.  <li>{{user}}</li>
4.  <li>{{arg}}</li>
5.  <li>{{plus}}</li>
6.</ul>

Now when you wish to use your new tag in a template, add "{{ load whatever }}" to load the tag then "{% app_list_of_stuff 5 %}" to use it. The "5" is just passed into the tag as the "arg" parameter.

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog