Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save janjouketjalsma/b0d37329bda32383f2ec7ba8b685a814 to your computer and use it in GitHub Desktop.
Save janjouketjalsma/b0d37329bda32383f2ec7ba8b685a814 to your computer and use it in GitHub Desktop.
Translate twig date extension (time_diff filter) to Dutch (Nederlands) using array loader in a custom non-symfony application
<?php
// Create translator for date diff
$translator = new Symfony\Component\Translation\Translator('nl_NL');
$translator->addLoader('array', new Symfony\Component\Translation\Loader\ArrayLoader());
$translator->addResource('array', array(
'diff.ago.second' => 'een seconde geleden|%count% seconden geleden',
'diff.ago.minute' => 'een minuut geleden|%count% minuten geleden',
'diff.ago.hour' => 'een uur geleden|%count% uur geleden',
'diff.ago.day' => 'een dag geleden|%count% dagen geleden',
'diff.ago.month' => 'een maand geleden|%count% maanden geleden',
'diff.ago.year' => 'een jaar geleden|%count% jaar geleden',
), 'nl_NL', 'date');
// Add extensions
$view->addExtension(new Twig_Extensions_Extension_Date($translator));
@sudofox
Copy link

sudofox commented Dec 2, 2020

For some reason my twig expects a Symfony\Component\Translation\TranslatorInterface instead of a Symfony\Component\Translation\Translator so this isn't working

@janjouketjalsma
Copy link
Author

janjouketjalsma commented Dec 3, 2020

@sudofox Could it be you didn't load the translator class? I don't remember which composer package is required but I can check it out later.

I would guess that translator implements the translator interface so it should work.

If you share your error log here I'll be happy to assist!

@janjouketjalsma
Copy link
Author

janjouketjalsma commented Dec 3, 2020

Hey @sudofox, just checked and Translator implements TranslatorInterface (see https://github.com/symfony/translation/blob/52f486a707510884450df461b5a6429dd7a67379/Translator.php#L92) so that should be no issue.

The package that is required for the Translator class is symfony/translation. Could you verify if it is installed? If you don't have it you can install it using: composer require symfony/translation.

If you are getting an error about Symfony\Component\Translation\TranslatorInterface then maybe you need a lower version of the translation package (I think <= 3.4) because in higher symfony versions the include path changed to: Symfony\Contracts\Translation\TranslatorInterface.

@sudofox
Copy link

sudofox commented Dec 3, 2020

Ah, I think my problem is that I'm using Twig without Symfony. I tried adding in those particular components but it failed, but I haven't tried adding in an older version. I'll give it a shot later. Might just write my own implementation of it though

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