On this page
Preprocessing and modifying attributes in a .theme file
This documentation needs work. See "Help improve this page" in the sidebar.
Just like Drupal 7, you can affect the output of certain HTML via preprocess functions. For example, if you wanted to add a class to a menu and preferred to do this at the PHP level you can.
This is a good way to alter theme-specific markup. If you want to make theme-independent markup you should add code to a custom module, where in place of mytheme.theme
you have mymodule.module
.
For the purposes of documentation here "mytheme" is the machine name of your theme; for example "bartik" is a theme machine name.
To work with preprocess functions:
- Create or edit a file in your theme directory called
mytheme.theme
- Create a function such as
mytheme_preprocess_HOOK
where HOOK refers to the item you wish to affect. HOOK names follow twig template suggestions. To create a hook forpage.html.twig
you createmytheme_preprocess_page
. To create a hook fornode--article.html.twig
you createmytheme_preprocess_node__article
(replacing dashes with underscores). To discover hook names, see Locating Template Files with Debugging. - Write your changes and save
- Rebuild the cache so your changes are available (if you have drush installed,
drush cr
on the command line)
Let's assume we wanted to add a class of my-menu
to all of the menus on your site. Assuming your theme is called "mytheme" you would write the following function:
/**
* Implements hook_preprocess_HOOK() for menu.html.twig.
*/
function mytheme_preprocess_menu(&$variables) {
// Allow the Attribute Class to deal with adding a css class to this element.
$variables['attributes']['class'][] = 'my-menu';
}
You could inspect the $variables object with a condition to determine which menu you are working with. The elements within $variables become available in twig after theme Pre-Processing.
So now to extend our example, let's assume we want to add the class "my-main-menu" to the main menu of your site. This would be the function to do so:
/**
* Implements hook_preprocess_HOOK() for menu.html.twig.
*/
function mytheme_preprocess_menu(&$variables) {
if ($variables['menu_name'] == 'main') {
$variables['attributes']['class'][] = 'my-main-menu';
}
}
Differences from Drupal 7
- There is no longer a
template.php
file. That file has been replaced bymytheme.theme
. However, it still functions in much the same way allowing for hooks to modify output.
Other helpful links
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion