Avoid widows using a template filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django.template import Library, Node

register = Library()

def widont(value):
    bits = value.rsplit(' ', 1)
    try:
        widowless = bits[0] + " " + bits[1]
        return widowless
    except:
        return value

register.filter(widont)

More like this

  1. Enhanced "avoid widows" template filters by SmileyChris 5 years, 10 months ago
  2. Filter to add zero-width space to break up long words by jayliew 9 months ago
  3. Pad integers with leading zeros (template filter) by jcroft 5 years, 5 months ago
  4. Auto HTML Linebreak filter by punteney 5 years, 2 months ago
  5. nbsp filter by vitamon 7 months, 1 week ago

Comments

obeattie (on February 27, 2007):

Thanks for this - looks like this could prove very useful!

#

paching (on March 1, 2007):

Nice little trick I didn't know about! Just a couple notes;

If there happens to be an HTML tag such as a link on the last word, this would break it. However for simple headers, I suppose this isn't a problem. In my own code I'm putting this inside a text conversion function where I'm already keeping track of tags, anyway :)

Also, it could be implemented as a simple one-liner:

return ' '.join(value.rsplit(' ', 1))

#

obeattie (on March 11, 2007):

Just one little gotcha...

The template should ensure that it is using a string... so Line 6 should read:

bits = str(value).rsplit(' ', 1)

Therefore, if an object which is not a string is passed to it, it's string method will be called to ensure that the filter will work as intended.

Otherwise, this is brilliant!

#

Amr Mostafa (on April 22, 2007):

Nice one! Thanks

#

SmileyChris (on July 25, 2007):

I've put a more advanced version of this at snippet 340

#

RobertPattinson (on August 6, 2012):

If there happens to be an HTML tag such as a link on the last word, this would break it. However for simple headers, I suppose this isn't a problem. In my own code I'm putting this inside a text conversion function where I'm already keeping track of tags, anyway :)
Thanks
BlackBerry Curve 9320 cases

#

ghantoby (on June 12, 2013):

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

agen sbobet, Judi, Modifikasi, Bokep Streaming, Casino, Poker

#

yakenzu (on June 16, 2013):

Thank you for another essential article. Where else could anyone get that kind of information in such a complete way of writing? I have a presentation incoming week, and I am on the lookout for such information. Jasa seo, Ghantoby

#

(Forgotten your password?)