diff --git a/src/TwigTweakExtension.php b/src/TwigTweakExtension.php index 53b11d1..756a26c 100644 --- a/src/TwigTweakExtension.php +++ b/src/TwigTweakExtension.php @@ -112,6 +112,7 @@ class TwigTweakExtension extends AbstractExtension { new TwigFilter('children', [self::class, 'childrenFilter']), new TwigFilter('file_uri', [self::class, 'fileUriFilter']), new TwigFilter('file_url', [self::class, 'fileUrlFilter']), + new TwigFilter('translation', [self::class, 'entityTranslation']), ]; if (Settings::get('twig_tweak_enable_php_filter')) { @@ -601,6 +602,22 @@ class TwigTweakExtension extends AbstractExtension { return \Drupal::service('twig_tweak.url_extractor')->extractUrl($input, $relative); } + /** + * Returns the translation for the given entity. + * + * @param \Drupal\Core\Entity\EntityInterface $entity + * The entity to get the translation from. + * @param string $langcode + * (optional) For which language the translation should be looked for, + * defaults to the current language context. + * + * @return \Drupal\Core\Entity\EntityInterface + * The appropriate translation for the given language context. + */ + public static function entityTranslation(EntityInterface $entity, string $langcode = NULL): EntityInterface { + return \Drupal::service('entity.repository')->getTranslationFromContext($entity, $langcode); + } + /** * Evaluates a string of PHP code. * diff --git a/tests/src/Functional/TwigTweakTest.php b/tests/src/Functional/TwigTweakTest.php index 46b3d65..5e07198 100644 --- a/tests/src/Functional/TwigTweakTest.php +++ b/tests/src/Functional/TwigTweakTest.php @@ -379,6 +379,11 @@ final class TwigTweakTest extends BrowserTestBase { $xpath = '//div[@class = "tt-file-url-from-media-field" and contains(text(), "/files/image-1.png")]'; $this->assertXpath($xpath); + // -- Entity translation. + // This is just a smoke test because the node is not translatable. + $xpath = '//div[@class = "tt-translation" and contains(text(), "Alpha")]'; + $this->assertXpath($xpath); + // -- Hook twig_tweak_functions_alter(). $xpath = '//div[@class = "tt-functions_alter" and text() = "-=bar=-"]'; $this->assertXpath($xpath); diff --git a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig index b4d292c..f08a755 100644 --- a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig +++ b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig @@ -97,6 +97,7 @@