I have the following code in my custom theme that works well and allows me to test against the multisite_id in my twig files:

function mytheme_preprocess_page(&$variables) {

 $site_path = \Drupal::service('site.path');  
 $site_path = explode('/', $site_path);
 $site_name = $site_path[1];
 $variables['multisite_id'] = $site_name;


I need the same functionality inside a module. I can't seem to access the multisite_id var from the module.

I'm new to module development. I can't seem to get the same preprocess hook to work from my .module file. Is there a different approach when using a module?

  • 1
    No there shouldn't be any difference. Did you clear caches? Did ensure the module is enabled? What template exactly are you working with? Where is it located? How are you accessing the variable exactly? After enabling Kint what did {{ kint() }} tell you?
    – leymannx
    Mar 26, 2020 at 22:22
  • You got the snippet from drupal.stackexchange.com/a/257333/15055, right?
    – leymannx
    Mar 26, 2020 at 22:25
  • @leymannx - Yes cleared cache and the module is enabled. I'm trying to use {{ multisite_id }} in the same module /templates/foo.html.twig. I'm accessing the variable the same way I do in other twig files {% if multisite_id == "foo" %}. And yes, I believe I got the code from the post you linked.
    – pburgh
    Mar 26, 2020 at 23:18
  • Do I have to uninstall/enable the module to pick up changes in the .module file?
    – pburgh
    Mar 26, 2020 at 23:41
  • 1
    As you are adding this to the $variables of preprocess_PAGE hook, it would ordinarily (only) be made available in /templates/page.html.twig. If you want it in templates/foo.html.twig, you can put this snippet in module_preprocess_foo(&$variables). (Note that theme hook suggestions will muddy this 1:1 correlation) Mar 27, 2020 at 1:26


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.