diff --git a/src/TwigExtension.php b/src/TwigExtension.php index 62f25ce..711a2ac 100644 --- a/src/TwigExtension.php +++ b/src/TwigExtension.php @@ -47,6 +47,7 @@ class TwigExtension extends \Twig_Extension { new \Twig_SimpleFilter('token_replace', [$this, 'tokenReplaceFilter']), new \Twig_SimpleFilter('preg_replace', [$this, 'pregReplaceFilter']), new \Twig_SimpleFilter('image_style', [$this, 'imageStyle']), + new \Twig_SimpleFilter('transliterate', [$this, 'transliterate']), ]; // PHP filter should be enabled in settings.php file. if (Settings::get('twig_tweak_enable_php_filter')) { @@ -382,6 +383,30 @@ class TwigExtension extends \Twig_Extension { } } + /** + * Transliterates text from Unicode to US-ASCII. + * + * @param string $string + * The string to transliterate. + * @param string $langcode + * (optional) The language code of the language the string is in. Defaults + * to 'en' if not provided. Warning: this can be unfiltered user input. + * @param string $unknown_character + * (optional) The character to substitute for characters in $string without + * transliterated equivalents. Defaults to '?'. + * @param int $max_length + * (optional) If provided, return at most this many characters, ensuring + * that the transliteration does not split in the middle of an input + * character's transliteration. + * + * @return string + * $string with non-US-ASCII characters transliterated to US-ASCII + * characters, and unknown characters replaced with $unknown_character. + */ + public function transliterate($string, $langcode = 'en', $unknown_character = '?', $max_length = NULL) { + return \Drupal::transliteration()->transliterate($string, $langcode, $unknown_character, $max_length); + } + /** * Evaluates a string of PHP code. * diff --git a/tests/src/Functional/TwigTweakTest.php b/tests/src/Functional/TwigTweakTest.php index dd03dfa..d776103 100644 --- a/tests/src/Functional/TwigTweakTest.php +++ b/tests/src/Functional/TwigTweakTest.php @@ -148,6 +148,10 @@ class TwigTweakTest extends BrowserTestBase { // Test image style. $xpath = '//div[@class = "tt-image-style" and contains(text(), "styles/thumbnail/public/images/ocean.jpg")]'; $this->assertByXpath($xpath); + + // Test transliteration. + $xpath = '//div[@class = "tt-transliterate" and contains(text(), "Privet!")]'; + $this->assertByXpath($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 c45610c..add9655 100644 --- a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig +++ b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig @@ -37,4 +37,5 @@
{{ 'Site name: [site:name]' | token_replace }}
{{ 'foo' | preg_replace('(foo)', '$1-bar') }}
{{ 'public://images/ocean.jpg' | image_style('thumbnail') }}
+
{{ 'Привет!' | transliterate('ru') }}