Score:0

How to send variables to a custom theme from a custom module

in flag

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 ?

4uk4 avatar
cn flag
region--content is not a custom template. Use a different name not derived from a core template.
Dynamdilshan avatar
in flag
@4uk4 I have tried with other names. I have a template named `course-list.html.twig`. Didn't work with that either.
in flag
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?
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.