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) |
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) |
Comments
Thanks for this - looks like this could prove very useful!
#
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:
#
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!
#
Nice one! Thanks
#
I've put a more advanced version of this at snippet 340
#