Django Template Tag for Truncating Characters at a Word Boundary

The default truncatechars template tag truncates a string if it is longer than the specified number of characters but does so exactly at the character count, irrespective of whether it’s the middle of a word or not.

Here’s a smarter version that clips the text at the word boundary:

Conditional Output of a Django Block

A common use case when developing Django templates is rendering a block only when the block has content. Take this for example:

If you use blocks as designed out of the box, you’ll end up with some extra markup that you may need to hide via other methods (such as CSS). That’s definitely not ideal.

After digging around for a bit I stumbled upon this very helpful snippet which accomplishes this using a custom template tag:

The tag captures the content of the block to a variable within the template which can then be tested for existence, allowing you to conditionally show the block depending on the contents.

Using the tag is as simple as this:

Hopefully Django adds this in the future.