Home > Django > Inclusion Tag

Inclusion Tag

While putting a site together I was trying to clean up the code a bit and insert a piece of logic in a couple places. In some frameworks this concept is called a “component.” Regardless, I found out that Django had this thing called an Inclusion Tag. Which allows you to insert the output from a function/template pair into another template.

The resources online confused me a bit, so here’s the summary of what you need to do.

First create a folder named “templatetags” within your application’s directory. Within that folder you will need to add two files, one named “__init__.py” and the other the name of your tags, I’ve named it “tags.py”. This name is important since it will be the way you call this piece of code. You will also need to add a template for this “component”, I named mine “temp_mesages.html”

The tags.py file looks like this:

from lamalo.microBlogApp.models
import Message Profile
from django import template

register = template.Library()

def show_messages(userProfile):
message_list = Message.objects.filter(profile=userProfile).order_by('-timestamp')[:5]
return {'message_list': message_list}

temp_messages.html looks like this

{% for message in message_list %}
<table border="1" width="100%">
<td>{{ message.timestamp|date:"F j, Y h:i:s A" }}: {{ message.text }}</td>
{% endfor %}

Now the code is ready to be used… The way that you make use of it is by first loading the tags.py by calling ‘load tags’ and then calling the function. This code goes within one of your templates:

{% load tags %}
{% show_messages userProfile %}
Categories: Django Tags:
  1. robert
    March 28th, 2008 at 00:55 | #1

    Hello !!!

    I am trying to think about the options to add components using django … I have three questions (hope the html works here :P ):

    I want to use the components in a multiple way, I mean can I have a component inside another component in django ?
    Can you leave there the full code ?
    What is the difference (in power) between custom tags and inclusion_tag method ? There is something that we can do with custom tag and we can’t with include_tag?

  2. August 30th, 2009 at 12:43 | #2

    I never ever post but this time I will,Thanks alot for the great blog.

  3. January 7th, 2011 at 04:56 | #3


    this post was helpful for me, so I wanted to thank you. Other recources sometimes confused me and they are not so clear.
    By the way: are you iranian?

    Best regards

  4. January 20th, 2011 at 16:35 | #4

    Ya, I am Iranian… My last name doesn’t really make it too easy to hide ;)

  1. No trackbacks yet.