foxfirefey: A fox colored like flame over an ornately framed globe (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()

@stringfilter
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/mytags.py 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.

This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

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

April 2014

S M T W T F S
  12345
6789101112
131415161718 19
20212223242526
27282930   

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags