TransExtension.php 1.9 KB

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