diff --git a/src/TwigExtension.php b/src/TwigExtension.php index 99e810d..31e6f3d 100644 --- a/src/TwigExtension.php +++ b/src/TwigExtension.php @@ -63,6 +63,7 @@ class TwigExtension extends \Twig_Extension { new \Twig_SimpleFilter('check_markup', [$this, 'checkMarkup']), new \Twig_SimpleFilter('truncate', [$this, 'truncate']), new \Twig_SimpleFilter('view', [$this, 'view']), + new \Twig_SimpleFilter('with', [$this, 'with']), ]; // PHP filter should be enabled in settings.php file. if (Settings::get('twig_tweak_enable_php_filter')) { @@ -647,6 +648,24 @@ class TwigExtension extends \Twig_Extension { return Unicode::truncate($string, $max_length, $wordsafe, $add_ellipsis, $min_wordsafe_length); } + /** + * Adds new element to the array. + * + * @param array $build + * The renderable array to add the child item. + * @param int|string $key + * The key of the new element. + * @param mixed $element + * The element to add. + * + * @return array + * The modified array. + */ + public function with(array $build, $key, $element) { + $build[$key] = $element; + return $build; + } + /** * Returns a render array for entity, field list or field item. * diff --git a/tests/src/Functional/TwigTweakTest.php b/tests/src/Functional/TwigTweakTest.php index 6de13da..603e93b 100644 --- a/tests/src/Functional/TwigTweakTest.php +++ b/tests/src/Functional/TwigTweakTest.php @@ -231,6 +231,10 @@ class TwigTweakTest extends BrowserTestBase { $xpath = '//div[@class = "tt-truncate" and text() = "Hello…"]'; $this->assertByXpath($xpath); + // Test 'with'. + $xpath = '//div[@class = "tt-with"]/b[text() = "Example"]'; + $this->assertByXpath($xpath); + // Test node view. $xpath = '//div[@class = "tt-node-view"]/article[contains(@class, "node--view-mode-default")]/h2[a/span[text() = "Beta"]]'; $xpath .= '/following-sibling::footer[//h4[text() = "Member for"]]'; 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 a371a5d..c22c0cc 100644 --- a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig +++ b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig @@ -52,6 +52,7 @@
{{ 'Привет!' | transliterate('ru') }}
{{ 'bold strong' | check_markup('twig_tweak_test') }}
{{ 'Hello world!'|truncate(10, true, true) }}
+
{{ {'#markup':'Example'}|with('#prefix', '')|with('#suffix', '') }}
{{ node|view }}
{{ node.title|view }}
{{ node.title[0]|view }}