diff --git a/src/TwigExtension.php b/src/TwigExtension.php index ba512f7..9e4b8c8 100644 --- a/src/TwigExtension.php +++ b/src/TwigExtension.php @@ -69,6 +69,7 @@ class TwigExtension extends \Twig_Extension { new \Twig_SimpleFilter('truncate', [$this, 'truncate']), new \Twig_SimpleFilter('view', [$this, 'view']), new \Twig_SimpleFilter('with', [$this, 'with']), + new \Twig_SimpleFilter('children', [$this, 'children']), ]; // PHP filter should be enabled in settings.php file. if (Settings::get('twig_tweak_enable_php_filter')) { @@ -717,6 +718,22 @@ class TwigExtension extends \Twig_Extension { return $build; } + /** + * Filters out the children of a render array, optionally sorted by weight. + * + * @param array $build + * The render array whose children are to be filtered. + * @param bool $sort + * Boolean to indicate whether the children should be sorted by weight. + * + * @return array + * The element's children. + */ + public function children(array $build, $sort = FALSE) { + $keys = Element::children($build, $sort); + return array_intersect_key($build, array_flip($keys)); + } + /** * 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 9d0104a..0f2b9eb 100644 --- a/tests/src/Functional/TwigTweakTest.php +++ b/tests/src/Functional/TwigTweakTest.php @@ -270,6 +270,10 @@ class TwigTweakTest extends BrowserTestBase { $xpath = '//div[@class = "tt-with"]/b[text() = "Example"]'; $this->assertByXpath($xpath); + // Test 'children'. + $xpath = '//div[@class = "tt-children" and text() = "doremi"]'; + $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 6c6bdf2..654fa95 100644 --- a/tests/twig_tweak_test/templates/twig-tweak-test.html.twig +++ b/tests/twig_tweak_test/templates/twig-tweak-test.html.twig @@ -56,6 +56,20 @@