NicholasByDesign
NicholasByDesign

Reputation: 799

Drupal 8 render custom theme from custom module

This used to work for me without fail when Drupal 8 first came out. However this does not seem to work anymore and I get an error. Drupal docs have always been horrid so no solution there.

custom.module

<?php

function custom_theme() {
    $theme['home_page'] = [
        'variables' => ['name' => NULL],
        'template' => 'home_page'
    ];

    return $theme;
}

function custom_menu(){
  $items = array();
  $items['admin/config/system/custom'] = array(
    'title' => 'Custom',
    'description' => 'Configuration Custom',
    'route_name' => 'custom.settings'
  );
  return $items;
}

custom.routing.yml

custom.home:
    path: /home
    defaults: 
        _controller: Drupal\custom\Controller\RoutingController::home
    requirements:
        _permission: 'access content'

src/Controller/RoutingController.php

<?php

namespace Drupal\custom\Controller;

class RoutingController {
    public function home(){
        return array(
            '#title' => 'Home',
            '#theme' => 'home_page'
        );
    }

}

home_page.html.twig

<main>
   <!-- some markup -->
</main>

Upvotes: 0

Views: 2025

Answers (1)

code.rider
code.rider

Reputation: 1907

your controller not extending the base controller class problem one
try this

namespace Drupal\custom\Controller;

use Drupal\Core\Controller\ControllerBase;

class RoutingController extends ControllerBase{
    public function home(){
        return array(
            '#title' => 'Home',
            '#theme' => 'home_page'
        );
    }

}

home_page.html.twig

<main>
   <!-- some markup -->
   {{ content }}
</main>

also try to extend you theme hook with path

'path' => drupal_get_path('module', 'custom') . '/templates',

and place your template twig file in your module/templates folder

Upvotes: 0

Related Questions