foxfirefey: Fox stealing an egg. (Default)
foxfirefey ([personal profile] foxfirefey) wrote in [community profile] django_dev2010-05-19 04:39 pm
Entry tags:

Example of a filter that adds HTML to a string

This is a filter that turned out to be not quite as useful as I thought because some of the phrases our graphic designer wanted more than one word bolded, but I could totally change around the argument of this filter to take in a number of words to enclose, instead of making the class the optional argument. But, I thought it made a good basic example, so I figured I'd post it. It's useful if you want to visually emphasize the first word of a string, since there's no CSS pseudoselector for that.

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape

register = template.Library()

def firstword(value, arg="firstword"):
    """Puts a span around the first word of a string, arg is an optional class,
    otherwise it's "firstword"."""

    fields = [conditional_escape(field) for field in value.partition(" ")]
    fields[0] = '<span class="%s">%s</span>' % (arg, fields[0])
    return mark_safe("".join(fields))

register.filter('firstword', firstword)

The above code can go into a file (example given) called templatetags/ into any installed application.

In the template you're using the filter, you'll need to {% load mytags %}. Then to call the filter: {{ "Experimental Protocols"|firstword }}.

Now, you'll note that this filter is designed to work on strings that contain no HTML, and it escapes all HTML in the words. This is because. However, you can read more about dealing about whether or not HTML is safe/escaped on the custom template tags guide--look for the initial_letter_filter example.