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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s