foxfirefey: Fox stealing an egg. (Default)
[personal profile] foxfirefey posting in [community profile] django_dev

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.

Anonymous( )Anonymous This account has disabled anonymous posting.
OpenID( )OpenID You can comment on this post while signed in with an account from many other sites, once you have confirmed your email address. Sign in using OpenID.
Account name:
If you don't have an account you can create one now.
HTML doesn't work in the subject.


Notice: This account is set to log the IP addresses of everyone who comments.
Links will be displayed as unclickable URLs to help prevent spam.


django_dev: The Django logo. (Default)
Developing with Django

April 2014

131415161718 19

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags