Decorating Blocks in Twig

This is a simple trick how you can dynamically decorate a block in Twig.

Let’s say your design has a fanzy sidebar but you only want to display it when it has some content. In Twig you would usually solve this creating two seperate base templates. One, which includes a block named “sidebar”, and another one without it. This is quite easy, but then you’ll have to make sure you’re using the right base template. In addition you’ll have to maintain two base templates, even if they’re identical except for the sidebar.

So is there something else we could do, to make life more easy? Sure, we could put some more logic into to base template: Let’s check if the sidebar block has content! In that case we will display the content of the block embedded in some extra HTML.

This is how a base.html.twig might look like:

{% set sidebarContent = block("sidebar") %}
{% if sidebarContent %}
	
{% endif %}

First we’re fetching the content of the block into a variable with Twig’s block function.  Now we can check if there’s some content in it, so we can display the HTML container and the sidebar content on demand. Note that you have to use the raw filter on the block content since it is already sanitized HTML.