Hello!

I tried to have a custom template for my page. I have tried a lot's of solution, but it's not working with my templates within the module.

From my_module.module I have

function my_module_theme($existing, $type, $theme, $path) {
    return array(
        'events_listing_display' => array(
            'variables' => array(
                'events' => NULL,
            ),
            'template' => 'events-listing-list',
        ),
    );
}

From my controller I have

        $events = 'test';
        
        return [
            '#theme' => 'events_listing_display',
            '#events' => $events,
        ];

and the events-listing-list.html.twig is in my_project/modules/custom/my_module/templates/

the error message I have is
Twig_Error_Loader: Template "themes/My_Theme/templates/events-listing-list.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "themes/My_Theme/templates/events-listing-list.html.twig" in the Drupal theme registry.). in Twig_Loader_Chain->getCacheKey() (line 115 of /var/www/my_project/vendor/twig/twig/lib/Twig/Loader/Chain.php).

I have clear the cached with drush cc and drush cc theme-registry.

It's working if I put the template file in the theme directory, but this is not what I want (there is no file in the theme directory when I tried to debug).

I do not understand what's wrong.

If anyone have an idea, it will be well appreciated!
Thanks.

Comments

jaypan’s picture

Where have you put the template?

Contact me to contract me for D7 -> D10/11 migrations.

fred974’s picture

I have put the events-listing-list.html.twig template in my_project/modules/custom/my_module/templates/

fred974’s picture

cnm1990’s picture

Are you still facing the same issue?
I tried above code and It is working fine for me.

I hope you are doing the same steps

  1. Create module_name.module file
  2. In that function define your hook_theme function
  3. function module_name_theme($existing, $type, $theme, $path) {
        return array(
            'events_listing_display' => array(
                'variables' => array('events' => NULL),
                'template' => 'event-listing-list',
            ),
        );
    }
  4. Create Controller Folder under src
  5. your controllername.php will look like
    <?php
    
    namespace Drupal\module_name\Controller;
    
    use Drupal\Core\Controller\ControllerBase;
    
    class EventController extends ControllerBase {
    
    	public function events () {
    		$events = "My Custom events";
            return [
            	'#theme' => 'events_listing_display',
            	'#events' => $events,
            ];
    	}
    }
  6. Create templates Folder and placed your "event-listing-list.html.twig" file
  7. Clear your cache.