ybup5a
Last Updated: February 25, 2016
·
4.794K
· havvg
985347f8d4d896aa17a3984d40971038

Symfony2 translating flash messages

Using $this->get('session')->getFlashBag()->set('success', 'your.translation.key'); is just so wrong.

If you are doing it that way, you possibly got a template reading something like this (from MopaBootstrapBundle):

{% macro flash(type, message, close, use_raw, class, domain) %}
    <div class="alert{{ type ? ' alert-'~type : '' }} fade in {{ class|default('') }}">
    {% if close|default(false) %}
        <a class="close" data-dismiss="alert" href="#">×</a>
    {% endif %}
    {% if use_raw|default(false) %}
        {{ message|trans({}, domain|default('messages'))|raw }}
    {% else %}
        {{ message|trans({}, domain|default('messages')) }}
    {% endif %}
    </div>
{% endmacro %}

What's wrong about that? How do you translate a pluralized message? This would be something like $this->get('session')->getFlashBag()->set('success', $this->get('translator')->transChoice('your.translation.key', $number, $parameters));

In this case, your template will "translate" a non-existing key: the translation result of your.translation.key.

Remember

  1. Stop passing in the translation key as a flash message.
  2. Pass in the translated message.
  3. Avoid translating non-existent translation keys.
  4. Clean code, clean applications, clean behaviors.
Say Thanks
Respond

1 Response
Add your response

2869
5959695565e8abec296e0f9d67a35343

I rather thoroughly agree with this post. Encountering a problem with the build of FOSUserBundle I'm using. Passing in the translation key rather than the translation makes it difficult to present the flash from a high-level template, shared by other bundles.

Interestingly enough, this thread didn't elicit this observation:
https://github.com/FriendsOfSymfony/FOSUserBundle/issues/246

That thread was closed, but I included my solution to that particular problem, if somebody else is google'ing for help.

over 1 year ago ·