Login

Add CSS class template filter

Author:
lazerscience
Posted:
November 8, 2010
Language:
Python
Version:
1.2
Tags:
django template tag css class template filter
Score:
2 (after 3 ratings)

Sometimes you want to add CSS classes to HTML elements that are generated by Django using their __unicode__ representation, eg. you can output a form field with {{ form.name }}, but if you would like to add a certain CSS class to the outputted input or select tag you would have to assort to plain HTML.

Using this filter you can simply do something like {{ form.name|add_class:"span-4" }} which will render an input like <input type="..." name="..." class="span-4.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import re
from django.utils.safestring import mark_safe
from django import template
register = template.Library()


class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')

@register.filter
def add_class(value, css_class):
    string = unicode(value)
    match = class_re.search(string)
    if match:
        m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class, 
                                                    css_class, css_class), match.group(1))
        print match.group(1)
        if not m:
            return mark_safe(class_re.sub(match.group(1) + " " + css_class, 
                                          string))
    else:
        return mark_safe(string.replace('>', ' class="%s">' % css_class))
    return value

More like this

  1. Django filter stack to cleanup WYSIWYG output by jbergantine 3 years, 10 months ago
  2. Dynamically add css-classes to formfields by Lacour 3 years, 11 months ago
  3. whitespaceoptimize block tag by peterbe 6 years, 9 months ago
  4. Pygmentify a code using template filter by tamizhgeek 4 years, 1 month ago
  5. Page numbers with ... like in Digg by Ciantic 6 years, 2 months ago

Comments

Please login first before commenting.