Easy Trick to Show Translation in a Twig Template Only if it Exists

I was building a web site for a client and I ran into a problem with translations. I needed to show a translated short description on a tag page, but not all of the tags had written descriptions.

The Problem

I was building a client site for a company that makes wallpapers. They have a huge listing of wallpapers in different categories (tags). For instance, take a look at all the baroque wallpapers they have.

On the tag page there's a short translated description of that category. The problem is, that all the categories don't necessarily have descriptions. If you try to show a translation that doesn't exist, the trans filter will just return the translation key.

Here's what the translations look like:

category:
	  barokki: Barokki ammensi vaikutteita...

If I try to load the page /tag/jugend/ the description would simply be category.jugend because the translation is missing. This is of course unacceptable.

The Solution

I was a bit surprised that I couldn't find a way to show an empty string if the translation key is not defined. I came up with a simple solution like this inside the twig template

{# Set the translation key #}
{% set translationKey = "category." ~ tag %}

{% if (translationKey | trans) != translationKey %}
   <p>{{ translationKey | trans }}</p>
{% endif %}

That does the trick. This piece of code will show the translation only if the trans filter returns something else than the translation key itself. Probably not the most elegant solution but it works for this use case.

Jaakko Naakka

Jaakko Naakka

Founder of Innota. Making web sites since 1996. Programming for a living in the middle of nowhere in Southern Finland.