Browse Source

Issue #3185016 by hanoii, Chi: Translation filter

3.1.x
Chi 4 years ago
parent
commit
7ec37ae520
  1. 17
      src/TwigTweakExtension.php
  2. 5
      tests/src/Functional/TwigTweakTest.php
  3. 1
      tests/twig_tweak_test/templates/twig-tweak-test.html.twig

17
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.
*

5
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);

1
tests/twig_tweak_test/templates/twig-tweak-test.html.twig

@ -97,6 +97,7 @@
<div class="tt-file-url-from-image-field">{{ node.field_image|file_url }}</div>
<div class="tt-file-url-from-image-field-delta">{{ node.field_image[0]|file_url }}</div>
<div class="tt-file-url-from-media-field">{{ node.field_media|file_url }}</div>
<div class="tt-translation">{{ (node|translation).title.value }}</div>
<div class="tt-functions_alter">{{ foo('bar') }}</div>
<div class="tt-filters_alter">{{ 'foo'|bar }}</div>
<div class="tt-tests_alter">{{ 'ok' is ok ? 'Yes' : 'No' }}</div>

Loading…
Cancel
Save