Skip to content

Dynamic Length Truncate Tag

by Paul Kenjora on April 2nd, 2008

Almost a year ago I wrote about Simple Character Truncate Filter And Dot Dot Dot Variant which was a basic string truncate written as a Django filter. It worked great until I needed to dynamically specify the length. Turns out filters are not good at resolving context variables (at least I dont know of a simple way). So to follow up the success of the original filter I’ve created a dynamic version implemented as a tag. Now you can specify any string and length (as a variable) and it will be truncated to that length in place.

Code

The implementation for the new tag only handles context variables, if you are hard coding the length just use a slice filter or the Simple Character Truncate Filter And Dot Dot Dot Variant instead.

dynamic_truncate_tag.py

sample.html

Final Thoughts

If anyone knows of a tag or another mechanism in Django that does this already definitely leave a comment. I’ve found this tag very useful for various widgets I’ve written, the tag was created specifically to add user control to the Arkayne Widget.

From → Filter, Template Tags

  • Rowena
    I am contacting you through this contact form as there was no email address available. We would be interested in purchasing advertising on your blog http://blog.awarelabs.com/. Please get back to me using the email address I have entered if you would be interested in discussing this further(rowenaseo@gmail.com).
  • This seems to work, to confirm SmileyChris:

    @register.filter
    def unfancy_truncate(value, arg):
    try:
    len = int(arg)
    return str(value)[:len]
    except:
    return ''
  • SmileyChris
    I'm sure {{ something|filter:obj.some_setting }} should just work. A tag seems overkill.
blog comments powered by Disqus