Django: Quick and easy template tags

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 "" 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:

from django.conf import settings
from django.template import Library

register = Library()

@register.inclusion_tag('app/list_of_stuff.html', takes_context = True)
def app_list_of_stuff(context, arg):
user = context['user']
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:

<ul class="list_of_stuff">

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