4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Bridge\Twig\Extension
;
14 use Symfony\Bridge\Twig\TokenParser\TransTokenParser
;
15 use Symfony\Bridge\Twig\TokenParser\TransChoiceTokenParser
;
16 use Symfony\Bridge\Twig\TokenParser\TransDefaultDomainTokenParser
;
17 use Symfony\Component\Translation\TranslatorInterface
;
18 use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor
;
19 use Symfony\Bridge\Twig\NodeVisitor\TranslationDefaultDomainNodeVisitor
;
22 * Provides integration of the Translation component with Twig.
24 * @author Fabien Potencier <fabien@symfony.com>
26 class TranslationExtension
extends \Twig_Extension
29 private $translationNodeVisitor;
31 public function __construct(TranslatorInterface
$translator, \Twig_NodeVisitorInterface
$translationNodeVisitor = null)
33 if (!$translationNodeVisitor) {
34 $translationNodeVisitor = new TranslationNodeVisitor();
37 $this->translator
= $translator;
38 $this->translationNodeVisitor
= $translationNodeVisitor;
41 public function getTranslator()
43 return $this->translator
;
49 public function getFilters()
52 'trans' => new \
Twig_Filter_Method($this, 'trans'),
53 'transchoice' => new \
Twig_Filter_Method($this, 'transchoice'),
58 * Returns the token parser instance to add to the existing list.
60 * @return array An array of Twig_TokenParser instances
62 public function getTokenParsers()
65 // {% trans %}Symfony is great!{% endtrans %}
66 new TransTokenParser(),
68 // {% transchoice count %}
69 // {0} There is no apples|{1} There is one apple|]1,Inf] There is {{ count }} apples
70 // {% endtranschoice %}
71 new TransChoiceTokenParser(),
73 // {% trans_default_domain "foobar" %}
74 new TransDefaultDomainTokenParser(),
81 public function getNodeVisitors()
83 return array($this->translationNodeVisitor
, new TranslationDefaultDomainNodeVisitor());
86 public function getTranslationNodeVisitor()
88 return $this->translationNodeVisitor
;
91 public function trans($message, array $arguments = array(), $domain = null, $locale = null)
93 if (null === $domain) {
97 return $this->translator
->trans($message, $arguments, $domain, $locale);
100 public function transchoice($message, $count, array $arguments = array(), $domain = null, $locale = null)
102 if (null === $domain) {
103 $domain = 'messages';
106 return $this->translator
->transChoice($message, $count, array_merge(array('%count%' => $count), $arguments), $domain, $locale);
110 * Returns the name of the extension.
112 * @return string The extension name
114 public function getName()