Problem/Motivation
\Drupal\Core\Template\TwigExtension::renderVar() will "render" and empty array or NULL or FALSE to a NULL. Once #3239860: \Drupal\Core\Template\TwigExtension::renderVar() can result in deprecations in PHP 8.1 lands this will change to rendering these values to an empty string.
\Drupal\Core\Template\TwigExtension::renderVar() is very permissive about what it excepts and returns. We have special handling for 0 float and integer values and it can return any scalar type, NULL or an object that implements \Drupal\Component\Render\MarkupInterface. Interestingly, I don't think it will ever return a \Twig\Markup object as per the docs :)
Note: the current behaviour is only depended on in core by Umami and Olivero because they both do things like
{% if page.pre_header|render|striptags|trim is not empty or
page.header|render|striptags|trim is not empty %}
<header class="layout-header" role="banner">
<div class="container">
{% if page.pre_header|render|striptags|trim is not empty %}
{{ page.pre_header }}
{% endif %}
{% if page.header|render|striptags|trim is not empty %}
{{ page.header }}
{% endif %}
</div>
</header>
{% endif %}
The use of |render|striptags|trim to decide whether to render something causes unexpected side-effects and should NOT be used. See #2937640: Umami theme ignores placeholders and HTML replaced elements when checking for empty regions. It is tempting to deprecate the behaviour so people have to fix their code to not do this.
Steps to reproduce
See test added by #3239860: \Drupal\Core\Template\TwigExtension::renderVar() can result in deprecations in PHP 8.1 - \Drupal\Tests\Core\Template\TwigExtensionTest::testRenderVarEarlyReturn
Proposed resolution
- Make the method return either a string or a \Drupal\Component\Render\MarkupInterface - i.e. a stringable.
- Decide how to handle unexpected input values. The docs say it expects
String, Object or Render Array.but the code is doing something else.
Comments
Comment #2
andypostComment #4
johnalbin