Quantcast
Channel: Issues for Drupal core
Viewing all articles
Browse latest Browse all 297510

Add a "context" array variable to all theme hooks (functions and templates) to provide optional contextual data

$
0
0

Problem/Motivation

Fairly often there is a need for some sort of contextual data when theming. It's possible in preprocess functions to add any variable you want, but when building render arrays you're limited to what's defined in hook_theme() and _template_preprocess_default_variables().

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):

<?php
    $build
['search_results'] = array(
     
'#theme'=> array('item_list__search_results__'. $plugin->getPluginId(), 'item_list__search_results'),
     
'#items'=> $results,
     
'#empty'=> array(
       
'#markup'=> '<h3>'. $this->t('Your search yielded no results.') . '</h3>',
      ),
     
'#list_type'=> 'ol',
     
'#cache'=> array(
       
'tags'=> $entity->getCacheTags(),
      ),
     
'#context'=> array(
       
'plugin'=> $plugin->getPluginId(),
      ),
    );
?>

Proposed resolution

Add 'context' => array(), to _template_preprocess_default_variables().

This could be slightly confusing when using the inline template #type, which uses #context to pass the variables to Twig. Opinions on whether that's confusing or not, or alternative names are welcome. Note that it's not actually a conflict because you can still pass a 'context' variable to an inline template if you really wanted, and inline templates don't go through preprocess, etc.

This is a "lite" version of #2121317: Introduce the "context" concept for theme system.

Remaining tasks

All of them

User interface changes

n/a

API changes

Small API addition.

Data model changes

None


Viewing all articles
Browse latest Browse all 297510

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>