Beta phase evaluation
<!--Uncomment the relevant rows for the issue. -->
Problem/Motivation
https://www.drupal.org/node/1806538 →
resolved that strict_variables
should not be enabled by default in Twig. This decision has allowed us to get sloppy in core themes. Core themes should reflect best practices and allow subthemes to use strict_variables
without throwing exceptions.
Our coding standards require
strict variables →
in JavaScript.
More details
In form-element.html.twig
, in the documentation says the description_display
variable exists:
...
* - description_display: Description display setting. It can have these values:
* - before: The description is output before the element.
* - after: The description is output after the element. This is the default
* value.
* - invisible: The description is output after the element, hidden visually
* but available to screen readers.
...
(note: not “optional” like the description
variable). However template_preprocess_form_element()
does not guarantee description_display
will be available in $variables
. The result is an exception if you enable any core theme and turn strict_variables
on.
Proposed resolution
If a variable is listed as "(optional)" in the template documentation, then the template should verify its existence before using it. Otherwise, the preprocess function should provide the variable – even if NULL – so that templates can be kept as clean as possible.
For example, if the documentation says that either foo
or foo.bar
is optional, then a template should use:
{{ foo.bar|default }}
or
{% if foo.bar|default is not empty %}
<div class="this-is-a-foo">{{ foo.bar }}</div>
{% endif %}
The more verbose (and potentially more readable to new users) version would be:
{{ foo.bar|default('') }}
or
{% if foo.bar is defined and foo.bar is not empty %}
<div class="this-is-a-foo">{{ foo.bar }}</div>
{% endif %}
But if the documentation says that foo.bar
is available, then a template should not need to check for it as the preprocess function should provide, at a minimum, a NULL placeholder.
{{ foo.bar }}
or
{% if foo.bar is not empty %}
<div class="this-is-a-foo">{{ foo.bar }}</div>
{% endif %}
Remaining tasks
- Update preprocess functions and Twig template documentation so that variables are correctly accounted for.
- Figure out if it's appropriate to turn on
strict_variables
on the testbot.
User interface changes
None.
API changes
None.