I'm trying to decouple drupal and get data via api calls so that I can use the same data across several drupal installs on different domains. So far I'm testing on the same domain but still can't figure out how to set my custom controller for node alias.
So far I've done the following
te.routing.yml
te.document_page:
path: '/documents/{document_name}'
defaults:
_controller: '\Drupal\te\Controller\DocumentController::documentPage'
requirements:
_permission: 'access content'
DocumentController.php
<?php
namespace Drupal\te\Controller;
use Drupal\Core\Controller\ControllerBase;
class DocumentController extends ControllerBase{
public function documentPage($document_name) {
$document = \Drupal::service('te.api')->get_single_document($document_name);
return [
'#theme' => 'te_document_page',
'#document_data' => $document,
];
}
}
I pass a document name to the function get_single_document() which makes a call to a rest route like so:
public function get($document_name) {
$response = 'node is not found';
$path = \Drupal::service('path_alias.manager')->getPathByAlias('/documents/'.$document_name);
if (preg_match('/node\/(\d+)/', $path, $matches)) {
$node = \Drupal\node\Entity\Node::load($matches[1]);
}
if (isset($node)) {
$response = $node;
}
return new ResourceResponse($response, 200);
}
So I get the needed node entity and pass it to my controller. However, drupal still renders default page.html.twig instead of my template passed in te.module
<?php
function te_theme($existing, $type, $theme, $path) {
return [
'te_document_page' => [
'variables' => [
'document_data' => NULL,
],
'file' => 'te.theme.inc',
'template' => 'document-page',
],
];
}
If I change my custom route to /whatever/{document_name} everything works fine. But with aliases generated and saved by pathauto module I can't get my template being used. I thought that maybe I have to alter routes with RouteSubscriber, but if I register the service and try to setDefault controller like so
protected function alterRoutes(RouteCollection $collection) {
$collection;
if ($route = $collection->get('entity.node.canonical')) {
$route->setDefault('_controller', '\Drupal\te\Controller\DocumentController::documentPage');
}
}
I get Access Denied error on routes mathing with aliases of nodes. What am I missing here?
page.html.twig
is way upper than the controller render template, and you cannot modify the render of the page easily with a controller. Maybe you have to implement a suggestion for your page template to use it.