On Drupal 8.9.x and successive Drupal versions, a theme can define its dependencies from modules. When that theme is installed, Drupal core will require that module to be installed, before allowing the theme installation. This means that when a theme template file is used, the require to use it.
Themes can declare dependencies on modules gives more details, but essentially that is done as it is done with modules. In the .info.yml file for the theme, it is sufficient to add lines like the following ones. (Replace <module>
with the module name, name-spaced, for example drupal:user
for the User module that is part of Drupal core, or twig_tweak:twig_tweak
for the Twig Tweak module.)
dependencies:
- <module>
If instead you want the theme to optionally depend on that module, you need to implement a preprocess function that is used for that template file. Since the question does not make clear which template file is used, I will make an example that is valid for the user.html.twig template file, but that can be adapted to other template files. (Replace <theme_name>
with the theme machine name.)
function <theme_name>_preprocess_user(&$variables) {
$variables['twig_tweak'] = \Drupal::moduleHandler()->moduleExists('twig_tweak');
}
Then, the template file should check the value of that variable.
{% if twig_tweak %}
{{ drupal_entity('block_content', 1) }}
{% else %}
{ # Show the content in a different way #}
{% endif %}
Since that module is an optional dependency, users should not see a message telling them to install a module when the module is not installed, which would probably be seen even from users who cannot install new modules on that site. Instead, the template file should shown alternative content, or show the same content in a different way.
If the same variable is required from more template files, instead of a preprocess function that is called for a single template file, I would implement <theme_name>_preprocess()
, which is called for every template file.