Previously, Drupal core's own template_process() was the only location in which default theme variables for all templates could be supplied. User module was hard-coded as an exception to provide the $user variable for all templates.
Starting with Drupal 8, all modules and themes can enhance the default theme variables for all templates through a new alter hook:
hook_template_preprocess_default_variables_alter()
This hook has been introduced to remove the hard-coded dependency on User module from template_preprocess().
Possible use-cases for this hook are very limited, since merely adding variables to the default theme variables will not cause them to be automatically used in any templates. It can, however, be helpful for modules that introduce some new concept for Drupal, which is extended by many other modules that may benefit from a new default theme variable in all templates provided by a base API module.
Note that the hook is only invoked once. The variables are statically cached for the rest of the request. If your module/theme adds variables that can change on other factors, then you are responsible for clearing the static variable when appropriate; e.g.:
/**
* Implements hook_user_login().
*/
function user_user_login($edit, $account) {
// Reset static cache of default variables in template_preprocess() to reflect
// the new user.
drupal_static_reset('template_preprocess');
}
Comments
Custom theme cannot implement that hook
I need to add an extra variable, then I tried to implement "hook_template_preprocess_default_variables_alter()" without success, then I double checked:
https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/_...
And it looks like this hook is only available to modules, then I took another way by implementing "hook_preprocess" but I am not sure if it's a good approach, any advice is welcome.
PD:
"ModuleHandler" service only manage modules, but themes should be sort by "ThemeHandeler"
Comment related: https://www.drupal.org/node/2486991#comment-11122813
Issue opened: https://www.drupal.org/node/2612196