Drupal has a complex rendering system and can be hard to understand for beginners. One of them is to understand theme suggestions.
For example, hooks like hook_theme_suggestions_HOOK_alter
and hook_theme_suggestions_HOOK
allow defining additional suggestions. It is fine to use in most cases. It gets complicated when you have a too-general hook with no specific data to add suggestions. A good example would be '#type' => 'links'
. It takes a list of links and inside suggestion hooks it is hard to determine, which kind of links list it is.
So, how can we add suggestions there? It seems to use #type
instead of theme too.
In the case of #type
, there is #theme, but it comes from the element definition, so in most cases, you can add #theme attribute. The value should match most of the time.
For the 'links' element, the default #theme
is 'links' . So, to assign suggestions without an extra hook, this can be defined like this:
$build['links'] = [
'#type' => 'links',
'#theme' => 'links__custom_links__my_module',
];
The attribute #theme
accepts pre-defined suggestions. They need to be separated by two underscores, and it will also split it into multiple theme suggestions, like:
links--custom-links--my-module.html.twig
links--custom-links.html.twig
links.html.twig
This trick should help in cases where quick theme suggestions are needed.