Updated: Comment #70
was started as a D7 issue, and is now a D8 issue (and assuming an eventual D7 backport). D8 fixes were partially addressed in . Most of the following was discussed with D8 in mind, but the decision was made to push the changes into D9.
All changes to
$variables that will be printed in templates currently happen in the same place, preprocess. Things that happen in preprocess include both creating initial variables and then altering those variables later. There is also inconsistency and confusion (for new themers) on when to use the module/theme name for
hook_ prefixing or the very ambiguous
Use a standard hook naming convention, exactly like the FAPI does. These standardized hooks would allow the theme system's phases to be split into a more systemic and easier to understand process. The two "phases" to add would be:
- A phase where the variables that are needed are prepared (created).
- A phase where anyone (modules or themes) can alter existing variables.
Add new prepare hooks. Add new prepare alter hooks. Create temporary tests for all the new hooks. Add new temporary method (
Drupal::moduleHandler()->themeInvoke()) to invoke hooks on active theme, similar to how
Keep backwards compatibility support for
hook_preprocess()by allowing it to run after the new API. Once everything is converted over, we don't have to worry about
hook_preprocess()phase in between the
hook_theme_prepare_alter()phases (per discussion about this via Twig hangout meeting/IRC
Deprecate hook_preprocess_HOOK() in API doc. Document hook_theme_prepare() in theme.api.php Add/change/remove subsections in theme() docblock. Add relevant
@todocomments for cleanup later.
Create test for hook_theme_prepare_THEME_HOOK__SUGGESTION().
- Add before/after example code in issue summary to demonstrate the benefits of this refactoring. (per #70)
User interface changes
Technically this is just one new "hook" with variations for allowing specific suggestion targeting. These specific hooks are invoked based on which template was used. For example
array('#theme' => 'node__page', ...), has two different
THEME_HOOKs. Two different prepare functions are called:
- hook_theme_prepare(&$variables, $hook)
- (and in a loop) hook_theme_prepare_THEME_HOOK(&$variables)
All hooks can be appended with
_alter for the altering "phase". This phase alters existing
$variables (added by the first phase above) by reference.
- hook_theme_prepare_alter(&$variables, $hook)
- (and in a loop) hook_theme_prepare_THEME_HOOK_alter(&$variables)
Mapping of Old API to New API
hook[template]_preprocess = hook_theme_prepare[_alter] hook[template]_preprocess_THEME_HOOK = hook_theme_prepare_THEME_HOOK[_alter] hook[template]_preprocess_THEME_HOOK__SUGGESTION = hook_theme_prepare_THEME_HOOK[_alter]
The last mapping is not actually not supported in old API. This issue would fix an existing critical bug for D8:.