Browse Source

Add 'children' filter

merge-requests/4/head
Chi 6 years ago
parent
commit
185c743ab4
  1. 17
      src/TwigExtension.php
  2. 4
      tests/src/Functional/TwigTweakTest.php
  3. 14
      tests/twig_tweak_test/templates/twig-tweak-test.html.twig

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

4
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"]]';

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

@ -56,6 +56,20 @@
<div class="tt-check-markup">{{ '<b>bold</b> <strong>strong</strong>' | check_markup('twig_tweak_test') }}</div>
<div class="tt-truncate">{{ 'Hello world!'|truncate(10, true, true) }}</div>
<div class="tt-with">{{ {'#markup':'Example'}|with('#prefix', '<b>')|with('#suffix', '</b>') }}</div>
<div class="tt-children">
{%-
set build = {
're': {'#markup': 're'},
'#sol': {'#markup': '#sol'},
'mi': {'#markup': 'mi'},
'#fa': {'#markup': '#fa'},
'do': {'#markup': 'do', '#weight': -10},
}
-%}
{%- for value in build|children(true) -%}
{{- value -}}
{%- endfor -%}
</div>
<div class="tt-node-view">{{ node|view }}</div>
<div class="tt-field-list-view">{{ node.title|view }}</div>
<div class="tt-field-item-view">{{ node.title[0]|view }}</div>

Loading…
Cancel
Save