zessx zessx - 2 months ago 19
PHP Question

Drupal 8 - routing file in theme

I'm a Drupal 7 regular user, but this is the first time I use Drupal 8.

I'm trying to define custom routes in my theme, but it seems my routing file is not taken into account. Here's my theme relevant files:

foo/
src/
Controller/
TestController.php
templates/
test/
list.html.twig
foo.routing.yml


With
foo.routing.yml
:

foo.test:
path: '/test-url'
defaults:
_controller: '\Drupal\foo\Controller\TestController::list'
_title: 'D8 routing test page'
requirements:
_permission: 'access content'


And
TestController.php
:

<?php

namespace Drupal\foo\Controller;

use Drupal\Core\Controller\ControllerBase;

class TestController extends ControllerBase
{

public function list() {
return array(
'#theme' => 'test/list.html.twig',
'#bar' => 'Variable transmission test'
);
}

}


The current result when I call
/test-url
is not my template, but the standard node page, with all fields displayed.

Am I missing something to make it work?

Answer

You should use theme name, not the template path in your render array:

public function list() {
    return array(
        '#theme' => 'list',
        '#bar'   => 'Variable transmission test'
    );
}

Also, by default, Drupal doesn't have 'list' theme, so you need to define it to (in your foo.theme file):

function foo_theme($existing, $type, $theme, $path) {
  return array(
    'list' => array(
      'variables' => array(
        'bar' => NULL
      )
    )
  );

UPD: @zessx addition: route declaration can be implemented in a module, not in a theme.

Comments