From 0f9c68957e4f86c765528ce21b0c420f5093a40e Mon Sep 17 00:00:00 2001 From: hanoii Date: Fri, 27 Nov 2020 09:31:11 +0000 Subject: [PATCH] Issue #3185016 by hanoii: Translation filter --- src/TwigExtension.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/TwigExtension.php b/src/TwigExtension.php index e6d3c38..726a3bc 100644 --- a/src/TwigExtension.php +++ b/src/TwigExtension.php @@ -393,6 +393,19 @@ class TwigExtension extends AbstractExtension { // {{ node.field_media|file_url }} // @endcode new TwigFilter('file_url', [$this, 'fileUrl']), + + // - Entity translation - + // + // Gets the translation of the entity for the current context. + // @code + // {{ node|translation }} + // @endcode + // + // An optional language code can be specified. + // @code + // {{ node|translation('es') }} + // @endcode + new TwigFilter('translation', [$this, 'entityTranslation']), ]; if (Settings::get('twig_tweak_enable_php_filter')) { @@ -1319,4 +1332,20 @@ class TwigExtension extends AbstractExtension { return $output; } + /** + * Returns the tranlation for the given entity. + * + * @param object $entity + * The entity to get the translation from. + * + * @param string $langcode + * (optional) For which language the trnaslation should be looked for, + * defaults to the current language context. + * + * @return EntityInterface + * The appropriate translation for the given language context. + */ + public function entityTranslation(EntityInterface $entity, $langcode = NULL) { + return \Drupal::service('entity.repository')->getTranslationFromContext($entity, $langcode); + } }