I had a problem. I needed to show a translated piece of text based on a route parameter. For instance, I wanted route `/category/symfony` to show a translated description of symfony.
What I tried was to create translations like this
category: symfony: Symfony is a framework and...
Now the problem I had is that I don't want to write descriptions to all of the categories. For instance, if I tried to access route `/category/twig` I would only see `category.twig` because the translation is missing.
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." ~ category %} {% 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.
March 7, 2017
© 2024 Jackdaw's Nest