Friday, August 24th, 2012

Bootstrap template filters for Django

Do you use bootstrap and Django together? If so, I have 2 powerful templatetags which may come in handy when developing your bootstrap enabled project. One filter turns a BooleanField result into a compatible bootstrap icon. The other filter can be used to display a specific amount of stars or any icon you can think of, I use this for rating stars.

If you do not have already, create a new template library, which is basically a templatetags Python package inside your app. In this Python package, create a new Python file which will contain the filter, that you can load into your templates. In this file, enter in the following code:

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

def yesnoicon(value):
    icon = "ok" if value else "remove"
    return mark_safe('<i class="icon-%s"></i>' % icon)

def ratingicon(value):
    return mark_safe('<i class="icon-star"></i>' * value)

There you have it, now in your templates you can load the template library and use the filters like so:

{% load bootstrap_filters %}


A super simple filter interface to make using bootstrap in Django that much easier. Enjoy!

About Me

My Photo
Names Kevin, hugely into UNIX technologies, not just Linux. I've dabbled with the demons, played with the Sun, and now with the Penguins.

Kevin Veroneau Consulting Services
Do you require the services of a Django contractor? Do you need both a website and hosting services? Perhaps I can help.

This Month

If you like what you read, please consider donating to help with hosting costs, and to fund future books to review.

Python Powered | © 2012-2019 Kevin Veroneau