While researching the newest object oriented hooks I found out it is possible to add Front Matter to Twig templates.
I thought it would be fun to create a hook that reads Front Matter and adds it as a variables.
Setup
I created a child theme of the default theme and named it test.
// test.info.yml
name: 'My Theme'
type: theme
description: 'A custom theme that inherits from Olivero'
core_version_requirement: ^11
base theme: olivero
To get the most visible change I picked the node processing hook. I already made an article content type. So that is going to be my experimentation page. And that is why I added the node--article.html.twig template to my theme.
---
test: testfdqfsqd
---
{{ test }}
The hook
In the test.theme file I wrote;
function test_preprocess_node(&$variables)
{
// Make sure no other templates are affected
if($variables['node']->getType() != 'article') {
return;
}
$suggestions = Drupal::service('module_handler')->invokeAll('theme_suggestions_node', [$variables]);
$template = '';
// get the first suggestion
foreach($suggestions as $suggestion) {
$file = str_replace('_', '-', $suggestion). '.html.twig';
if(file_exists(__DIR__. '/templates/' .$file)) {
$template = $file;
break;
}
}
$metadata = Drupal::service('twig')->getTemplateMetadata($template);
foreach($metadata as $name => $value) {
$variables[$name] = $value;
}
}
I stole the $suggestions
line from the ThemeManager
buildThemeHookSuggestions method.
Real world applications
While this code needs refinement before it is production ready.
And adding variables is not the best way to make use of this feature.
I think there could be occasions where this is a solution.
For front-enders this could be a way to preprocess variables.
It could be a way to create documentation for the template by adding example values to Front Matter.