Add a "context" array variable to all theme hooks and "#context" array property to all elements to provide optional contextual data

Created on 24 June 2015, over 9 years ago
Updated 13 September 2024, 3 months ago

Problem/Motivation

Fairly often there is a need for some sort of contextual data when rendering an element, which parts of, ultimately needs to make its way down the theme system pipeline.

This is especially true when certain render elements or theme hooks, that are not normally aware of the context in which they'll be rendered, needs additional information to provide rendering variations (i.e. per type or identifier).

While it is possible to add any variable you want in preprocess functions, it is often too late in the process and the original data that usually contains the needed information has long since been lost.

This is, in part, due to arbitrary properties (not registered in the theme hook) from being automatically transferred from a renderable element's properties.

Example from the search module in core, where a 'context' variable was manually added to allow for this flexibility ( #2495419: Move the 'search-results' class from the render array and into a Classy template โ†’ ):

$build['search_results'] = [
  '#theme' => ['item_list__search_results__' . $plugin->getPluginId(), 'item_list__search_results'],
  //...
  '#context' => ['plugin' => $plugin->getPluginId()],
];

Another example of use is for Views suggestions (which this issue is blocking): ๐Ÿ“Œ [PP-1] Use hook_theme_suggestions in views Postponed .

Proposed resolution

Add a context variable as an empty array for all theme hooks, if one doesn't already exist.

Add a #context property as an empty array to all elements, if one doesn't already exist.

Remaining tasks

User interface changes

None

API changes

  • The addition of a default #context property added to all elements
  • The addition of a default context property added to all theme hooks (for preprocessing purposes only)
  • The automatic mapping of a renderable element's #context property to the context variable
  • Removal of the context variable immediately prior to rendering (for security concerns).

Data model changes

None

โœจ Feature request
Status

Needs work

Version

11.0 ๐Ÿ”ฅ

Component
Themeย  โ†’

Last updated about 18 hours ago

Created by

๐Ÿ‡จ๐Ÿ‡ฆCanada star-szr

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

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024