diff --git a/core/lib/Drupal/Core/Render/Element/Container.php b/core/lib/Drupal/Core/Render/Element/Container.php index 5fd6fa0..7989ba4 100644 --- a/core/lib/Drupal/Core/Render/Element/Container.php +++ b/core/lib/Drupal/Core/Render/Element/Container.php @@ -53,6 +53,7 @@ public function getInfo() { ], '#pre_render' => [ [$class, 'preRenderGroup'], + [$class, 'preRenderContainer'], ], '#theme_wrappers' => ['container'], ]; @@ -81,10 +82,16 @@ public static function processContainer(&$element, FormStateInterface $form_stat } /** - * {@inheritdoc} + * Prevents optional containers from rendering if they have no children. + * + * @param $element + * An associative array containing the properties and children of the + * container. + * + * @return + * The modified element. */ - public static function preRenderGroup($element) { - $element = parent::preRenderGroup($element); + public static function preRenderContainer($element) { // Do not render optional container elements if there are no children. if (isset($element['#parents'])) { $group = implode('][', $element['#parents']); diff --git a/core/tests/Drupal/Tests/Core/Render/Element/ContainerTest.php b/core/tests/Drupal/Tests/Core/Render/Element/ContainerTest.php new file mode 100644 index 0000000..3f71cdc --- /dev/null +++ b/core/tests/Drupal/Tests/Core/Render/Element/ContainerTest.php @@ -0,0 +1,63 @@ +assertEquals($expected, (string) $this->renderer->renderRoot($result)); + } + + /** + * Data provider for preRenderContainer test. + */ + public function providerPreRenderContainer() { + $containers = []; + + // Empty optional container. + $element = [ + '#type' => 'container', + '#optional' => TRUE, + ]; + $element['child1'] = ['#markup' => '']; + $containers['empty-optional'] = [$element, '']; + + // Non-empty optional container. + $element = [ + '#optional' => TRUE, + ]; + $element['child1'] = ['#markup' => 'nested value']; + $containers['non-empty-optional'] = [$element, '
nested value
']; + + // Empty non-optional container. + $element = [ + '#type' => 'container', + '#optional' => FALSE, + ]; + $element['child1'] = ['#markup' => '']; + $containers['empty-non-optional'] = [$element, '
']; + + // Non-empty non-optional container. + $element = [ + '#type' => 'container', + '#optional' => FALSE, + ]; + $element['child1'] = ['#markup' => 'nested value']; + $containers['non-empty-non-optional'] = [$element, '
nested value
']; + + return $containers; + } + +}