in Tips

Symfony2 – Translation in the right way

Many times when project is almost done, customer brings you a “a great new idea”  and say:

My website will be international so I want to be translated on many languages!

And they give you few days to done that task, so you must turn on your super powers and do all magic that you know.  Fortunately there is one great thing, that you can do with Symfony 2 framework.  So let’ the magic begin!

First you need to install this 2 bundles to your Symfony2 app :

http://jmsyst.com/bundles/JMSI18nRoutingBundle

and

http://jmsyst.com/bundles/JMSTranslationBundle

Simple installation is that you just add this lines to your composer.json file :

"require":
  {
    "jms/i18n-routing-bundle": "dev-master",
    "jms/translation-bundle": "1.1.*"
  }

Then you just run:

php composer.phar update

After that, you need to enable the bundles in your AppKernel.php

$bundles = array (
    ...
    new JMS\I18nRoutingBundle\JMSI18nRoutingBundle(),
    new JMS\TranslationBundle\JMSTranslationBundle(),
);

And you need to edit your app/config/config.yml

jms_i18n_routing:
default_locale: en 
locales: [de, en, sr] 
strategy: prefix_except_default

And now, you need to say magic word, “Open sesame”, and you have 3 languages enabled on your site!

If you want to see that, you can type in console:

php app/console router:debug

There you can see all your new routes, for different languages.

Now, you will ask how to translate all text?

Well the easiest way is to use Symfony2 command line:

php app/console translation:extract de --bundle=AcmeDemoBundle --enable-extractor=jms_i18n_routing --output-format=yml --exclude-dir=Tests

If you get some error, just add this on the end and try again

--exclude-dir=Features

“It’s alive! It’s alive!”

You need to repeat that for all your bundles, that is only for AcmeDemoBundle.

After all that, you will get files in src/AppName/AppNameBundle/Resources/translations/

There you can add you translations.

And here I give you one example of language switcher, that you can implement in your app :

Screenshot_2

And here is one example if you want to translate one word from .twig template

{% trans %}Your Word{% endtrans %}

And in yout /translate/message.en.yml, you just need to put like this:

Your Word: Ihr Wort

And this will be translated to German.

 

Possible errors : 
When you change language and try to logout, you may get error like :
You must activate the logout in your security firewall configuration.

All you need to do is go to
\app\config\security.yml

and in firewals add this for logout

logout:
    path: fos_user_security_logout
    target: /admin

Thank you for reading and if you get stuck, please write in comment.

Till next time, “Be well, do good work, and keep in touch!”.

Share this ...Tweet about this on TwitterShare on FacebookEmail this to someoneShare on RedditShare on Google+Share on LinkedInPin on Pinterest
  • Vlad

    That doesn’t work…