It’s incredible how easy Django makes it for you finishing small tasks simple and fast. Django really comes with batteries included.
While re-writing the whole site in HTML with 52framework , I kind of missed one thing:
A category list.
I think it’s best to use Django‘s template tags for this job, as my template tag currently has to do one simple thing:
Return all existent categories(no matter if they have or not have references to any blog post).
I start doing this by creating a folder named templatetags in my blog application.
Never forget the __init__.py
Then I’ll go and create a file called get_category_list.py, the template tag file itself.
# -*- mode: python; coding: utf-8; -*-
from django import template
from blog.models import Post, Category
register = template.Library()
def category_list():
categories = Category.objects.all()
return {'categories': categories}
register.inclusion_tag('templatetags/category_list.html')(category_list)
I think it’s very self-explanatory. I create a function which returns a dictionary containing a Category object dictionary, containing all existing categories. You can specify that behavior by .filter() it or write a custom manager. You get the point.
Now the interesting part is the last line. We decorate our function with the register.inclusion_tag() decorator. Why using inclusion_tag? you may ask. Well I use it here for a certain convenience for later including the category_list.html in any template I’d like and writing less code, which means better quality to me.
Next step from here is to create the category_list.html in your templatetags folder.
Writing the content is dead simple. It may look like this:
<ul id="category-list">
{% for category in categories %}
<li class="align_center">
<a href="{% url whatever_reverse_url %}" title="{{ category.title }}">
{{ category.title }}
</a>
</li>
{% endfor %}
</ul>
and the last step is to include this anywhere in your templates.
{% load get_category_list %}
<header>
<h2>Categories</h2>
{# category_list was added to the template's context #}
{% category_list %}
</header>
In the next part, I’ll eventually show you how to get to number of posts with the category name.
Be sure to leave a comment!
