0

I'm trying to pass a variable from a custom module to a custom theme. I have a Controller class in a custom module

<?php

namespace Drupal\course_catalog\Controller;

use Drupal\Core\Controller\ControllerBase;

Class CourseCatalog extends ControllerBase {
  public function build() {

    $item = 'Test content';

    return [
      '#theme' => 'region__content',
      '#item' => $item,
    ];
  }
}

And this hook_theme() in the .module

<?php

/**
 * Implements hook_theme().
 */
function course_catalog_theme() {
  return [
    'region__content' => [
      'variables' => ['item' => NULL]
    ]
  ];
}

Lastly I have my custom theme I have region--content.html.twig

<h2>Content: {{ item }}</h2>

This item value never render on the page. Have I missed something here ?

3
  • region--content is not a custom template. Use a different name not derived from a core template.
    – 4uk4
    Aug 31, 2023 at 15:22
  • @4uk4 I have tried with other names. I have a template named course-list.html.twig. Didn't work with that either. Aug 31, 2023 at 21:59
  • Is the twig file located in the templates folder? Have you tried using {{ dump(item) }} to see what is inside the variable? And have you cleared Drupal cache?
    – Denis K
    Sep 1, 2023 at 14:46

1 Answer 1

0

Below Should work. In your hook_theme inside .module, set the variable you want as array or value in the variables.

$item = 'Test content';
'variables' => [
      'content' => 'content value from .module hook_theme ',
      'item' => $item,
       
    ],

Check the spelling of template file inside .module file or controller and that it actually exists in /templates.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.