Code Snippets and More

First of all we have to connect our Twig extension with the translation service. We have to configure the dependency injection container to do that.

Prepare the dependency injection container to load the configuration from an XML file

# Test/DemoBundle/DependencyInjection/TestDemoExtension.php

namespace Test\DemoBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\Config\FileLocator;

class TestDemoExtension extends Extension
    public function load(array $configs, ContainerBuilder $container)
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));

    public function getAlias()
        return 'test_demo';

Connect the Twig extension engine with the translator service (create an XML config file Test/DemoBundle/Resources/config/twig.xml)

<?xml version="1.0" ?>
<container xmlns=""

        <service id="twig.extension.test.demo" class="Test\DemoBundle\Twig\Extension\DemoExtension" public="false">
            <tag name="twig.extension" />
            <argument type="service" id="translator" />

Build the Twig extension with the translator as a parameter

# Test/DemoBundle/Twig/Extension/DemoExtension.php

namespace Test\DemoBundle\Twig\Extension;
use Symfony\Component\Translation\TranslatorInterface;

class DemoExtension extends \Twig_Extension
    protected $translator;

     * Constructor method
     * @param TranslatorInterface $translator
    public function __construct(TranslatorInterface $translator)
        $this->translator = $translator;

     * {@inheritdoc}
    public function getFunctions()
        return array(
            'translate' => new \Twig_Function_Method($this, 'translate')

     * Dummy function, translates a text
     * @return string
    public function translate ($text)
        return $this->translator->trans($text);

And thats all! We can use our new i18n method into all of our DemoBundle Twig templates

Do not forget to activate the i18n in the app/config/config.yml

    translator:      { fallback: %locale% }

Recent comments

© 2014 Copyright by Keyvan Akbary