Silex, Twig and Translation support

Silex, Twig and Translation support

As I have written a couple of days ago, we are using Silex and Twig to build a small of for one of our customers. Since the project was in need of I18N support, we set up the TranslationServiceProvider with the Symfony/Translation component as the Silex documentation advised. Unfortunately I was not able to find a Twig extension allowing us to translate static content within a Twig template, so it was the time to jump in and develop an extension on my own and publish it on github. Simply drop the files in your vendors directory and include the lib/bitExpert/Silex/Autoloader.php file within your application and execute the steps listed below:

1. Setup Symfony/Translation provider:

$app->register(new Silex\Provider\TranslationServiceProvider(), array(
'locale_fallback' => 'en',
'translation.class_path' => 'vendor/symfony/src',
$app['translator.messages'] = array(
'en' => 'locales/en.yml',
'de' => 'locales/de.yml'
$app['translator.loader'] = new Symfony\Component\Translation\Loader\YamlFileLoader();

2. To configure Twig, add the following lines to your index.php:

$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/views',
'twig.class_path' => __DIR__.'/vendor/twig/lib'

3. Finally we need to register the custom extension in Twig:

$app['twig']->addExtension(new bitExpert_Silex_Twig_Translation_Extension());

Using the translation extension within a twig template is quite simple:

{% translate my_translation_key %}

This will pass my_translation_key to Symfony/Translation and render the result within the twig template.

Eintrag von Stephan Hochdörfer am 07.03.2012

Tags: Allgemein, PHP, Symfony

Diese Webseite verwendet Cookies, um die Bedienfreundlichkeit zu erhöhen. Mit der Nutzung unserer Webseite wird das Einverständnis erklärt, dass wir Cookies verwenden. Weitere Informationen.