TranslationExtension.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\Extension;
  11. use Symfony\Bridge\Twig\TokenParser\TransTokenParser;
  12. use Symfony\Bridge\Twig\TokenParser\TransChoiceTokenParser;
  13. use Symfony\Component\Translation\TranslatorInterface;
  14. /**
  15. * Provides integration of the Translation component with Twig.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class TranslationExtension extends \Twig_Extension
  20. {
  21. private $translator;
  22. public function __construct(TranslatorInterface $translator)
  23. {
  24. $this->translator = $translator;
  25. }
  26. public function getTranslator()
  27. {
  28. return $this->translator;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function getFilters()
  34. {
  35. return array(
  36. 'trans' => new \Twig_Filter_Method($this, 'trans'),
  37. 'transchoice' => new \Twig_Filter_Method($this, 'transchoice'),
  38. );
  39. }
  40. /**
  41. * Returns the token parser instance to add to the existing list.
  42. *
  43. * @return array An array of Twig_TokenParser instances
  44. */
  45. public function getTokenParsers()
  46. {
  47. return array(
  48. // {% trans "Symfony is great!" %}
  49. new TransTokenParser(),
  50. // {% transchoice count %}
  51. // {0} There is no apples|{1} There is one apple|]1,Inf] There is {{ count }} apples
  52. // {% endtranschoice %}
  53. new TransChoiceTokenParser(),
  54. );
  55. }
  56. public function trans($message, array $arguments = array(), $domain = "messages")
  57. {
  58. return $this->translator->trans($message, $arguments, $domain);
  59. }
  60. public function transchoice($message, $count, array $arguments = array(), $domain = "messages")
  61. {
  62. return $this->translator->transChoice($message, $count, $arguments, $domain);
  63. }
  64. /**
  65. * Returns the name of the extension.
  66. *
  67. * @return string The extension name
  68. */
  69. public function getName()
  70. {
  71. return 'translator';
  72. }
  73. }