Skip to content

Instantly share code, notes, and snippets.

@kalmanolah
Created November 25, 2013 10:43
Show Gist options
  • Save kalmanolah/7639495 to your computer and use it in GitHub Desktop.
Save kalmanolah/7639495 to your computer and use it in GitHub Desktop.
Twig extension for translating arrays in Symfony2. Works just like the regular 'trans' filter, but takes an array as input instead.
<?php
namespace Your\ExampleBundle\Twig;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Twig extension for translating arrays in Symfony2
* Works just like the regular 'trans' filter, but takes an array as input instead
*
* your.examplebundle.translation_extension:
* class: Your\ExampleBundle\Twig\TranslationExtension
* tags:
* - { name: twig.extension }
* arguments:
* translator: "@translator"
*
* @author Kalman Olah <hello _at_ kalmanolah _dot_ net>
*/
class TranslationExtension extends \Twig_Extension
{
/**
* Constructs the service
*
* @param TranslatorInterface $translator Translation service implementing the translation interface
*/
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
/**
* @{inheritdoc}
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('transArray', array($this, 'transArrayFilter')),
);
}
/**
* Translates each element of an array using the provided translator
*
* @param array $ids An array of message ids (may also be an array of objects that can be cast to string)
* @param array $parameters An array of parameters for the messages
* @param string $domain The domain for the messages
* @param string $locale The locale
*
* @return array An array of (hopefully) translated messages
*/
public function transArrayFilter(
array $ids,
array $parameters = array(),
string $domain = null,
string $locale = null
) {
array_walk($ids, function(&$id) use ($parameters, $domain, $locale) {
$id = $this->translator->trans($id, $parameters, $domain, $locale);
});
return $ids;
}
/**
* @{inheritdoc}
*/
public function getName()
{
return 'translation_extension';
}
}
@MlleDelphine
Copy link

+1 !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment