Allow theme preprocess hooks to abort rendering

Created on 9 August 2023, about 1 year ago
Updated 22 December 2023, 9 months ago

Problem/Motivation

It would be very useful if preprocess hooks could prevent or abort the rendering completely.

To give some context, I was using this "hack" on 2 projects to prevent rendering empty regions, fields, layouts and paragraphs.
As an example, here is the preprocess I was using to prevent empty regions to render (sidebars for example):

function mymodule_preprocess_region(&$variables, $hook, &$info) {
  if (empty($variables['content'])) {
    $info['function'] = '';
  }
}

The method is convenient because in many cases, it is not easy at all to inject a #pre_render callback when the render array is built (which does have a way to prevent rendering) but that hack is no longer possible due to the changes from:
- #2760659: Allow the use of callbacks instead of global functions in preprocess function callbacks : call_user_func_array() now prevents passing the $info var as reference and modifying it.
- #3097889: Remove deprecated theme functions : is even more problematic since it removed theme functions which the hack was relying on.

Another advantage of this hack is that it skips the twig template to be rendered.
When any twig template is rendered, and if you have twig debug enabled, the debug part (HTML comments) will always be output which in many cases, can be annoying and tricky to detect emptiness.
This can apply for regions, fields, layouts, for example or any theme hook rendered with a twig template which may end up outputting nothing.
Example:

$region = [
  '#theme' => 'region',
  '#region' => 'region_name',
];
print (\Drupal::service('renderer')->renderPlain([
  '#theme' => 'region',
  '#region' => 'region_name',
]));

=> we get the twig debug part (HTML comments).

Proposed resolution

I'd like to hear some ideas on how to solve these kind of issues.
But I see 2 potential changes:
1. Alow preprocess hooks to abort rendering, by passing $variables['#abort_render'] = TRUE; for example.
2. Change twig_render_template() so that it won't output anything (twig debug HTML comments) when the render output is empty.

Remaining tasks

TODO

User interface changes

TODO

API changes

TODO

Data model changes

TODO

Release notes snippet

TODO

Feature request
Status

Active

Version

11.0 🔥

Component
Theme 

Last updated about 1 hour ago

Created by

🇧🇪Belgium herved

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024