gremo
gremo

Reputation: 48899

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

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>

Upvotes: 12

Views: 10579

Answers (4)

Anoop G
Anoop G

Reputation: 71

You can use twig extension to confirm translation exists or not.

$locale = $translator->getLocale();
$catalogue = $translator->getCatalogue($locale);
$id = 'bank_transaction_history.transfer.' . $resultCode;
if ($catalogue->defines($id)) {
    return $translator->trans($id);
}

Upvotes: 7

lhache
lhache

Reputation: 1909

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.

Upvotes: 17

Vitalii Zurian
Vitalii Zurian

Reputation: 17976

I've analyzed your problem and looked through the default Translator that is used in Symfony2.

It uses method trans() which is implemented like this.

For you the best workaround would be to redefine this method to return false, when you expect it.

Telling the long story short:

  1. Write your class, that implements TranslatorInterface and extends Translator

  2. Redefine method trans() there

  3. Define service as a translator with your Class (it will replace default translator with yours)

That's it

I hope it helps ;)

Upvotes: 1

Max Małecki
Max Małecki

Reputation: 1702

try to assign the string 'nav.' ~ route to the variable, and next translate the variable.

Upvotes: -1

Related Questions