Archive

Archive for March 7th, 2008

Inclusion Tag

March 7th, 2008 4 comments

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()

@register.inclusion_tag('temp_messages.html')
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%">
<tr>
<td>{{ message.timestamp|date:"F j, Y h:i:s A" }}: {{ message.text }}</td>
</tr>
</table>
{% 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: