Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a translation item exists in Twig/Symfony2?

Tags:

twig

symfony

Here is my macro for printing a sidebar item. Each title atttribute is build looking for 'tip.' ~ route item in messages.it.yml.

Even if the trans item does not exist Twig always return the string passed to trans filter. For example:

tip:
    dashboard: Dashboard

Template:

{% _self.sideitem('dashboard', 'home') %} // <a title="Dashboard">...
{% _self.sideitem('fail', 'home') %}      // <a title="tip.fail">...

{% macro sideitem(route, icon) %}
    {% set active = (route == app.request.get('_route')) %}
    {% set icon = icon ? 'icon-' ~ icon ~ (active ? ' icon-white' : '') : '' %}

    <li class="{{ active ? 'active' : '' }}">
        <a href="{{ path(route) }}" title="{{ ('tip.' ~ route)|trans }}">
            <i class="{{ icon }}"></i> {{ ('nav.' ~ route)|trans }}
        </a>
    </li>
{% endmacro %}

How can i check if a trans item exists before actually print it?

EDIT: a brutal workaround could be (code not tested):

<li class="{{ active ? 'active' : '' }}">
    {% set look    = ('tip.' ~ route) %}
    {% set foreign = look|trans %}
    {% set has     = not(look == foreign) %}

    <a href="{{ path(route) }}" {{ not has ? '' : 'title="' ~ foreign ~ '"'  }} >
        <i class="{{ icon }}"></i> {{ ('nav.' ~ route)|trans }}
    </a>
 </li>
like image 524
gremo Avatar asked Mar 09 '12 18:03

gremo


1 Answers

The solution I came up with was this one:

{% if "#{var}.something"|trans != "#{var}.something" %}

This just checks if the result of the translation key is different from the translation key itself. If a key has no translation, the "trans" filter returns the translation key.

like image 66
lhache Avatar answered Oct 21 '22 01:10

lhache