I have a Drupal 8 custom module, and I want to display its configuration page using the admin theme.
Usually, for this kind of pages I use, in the _controller
property of my route, rather :
- a class that extends
\Drupal\Core\Form\ConfigFormBase
(for a simple form-like config page) - a custom controller that extends
\Drupal\Core\Controller\ControllerBase
and returns a renderable array
For this module, I need to use complex HTML structure and a Javascript library for its configuration page. Writing all this directly in a #markup
property of a render array would be too much work and highly not-maintainable.
Is it possible to write a custom template (twig or not), to render it programmatically and insert the result into a container
element or in a #markup
property ?
And, as I use the Seven admin theme, I would like to do this without affecting the theme.
[Resolved] Final solution :
Combining leymannx answer and the elements mentioned below, I ended up with something that meet my requirements.
mymodule.routing.xml
mymodule.admin_ro:
path: '/admin/config/mymodule/readonly'
defaults:
_controller: '\Drupal\mymodule\Controller\ReadOnlyController::index'
_title: 'Module configuration - read only'
requirements:
_permission: 'view mymodule configuration'
options:
_admin_route: TRUE
no_cache: TRUE
ReadOnlyController.php
class ReadOnlyController extends ControllerBase {
public function index(){
return array(
'#type' => 'container',
'#theme' => 'test-template',
'#test_var' => [ 0, 1, 2, 3 ] // I needed an array type variable
);
}
}
mymodule.module
// Implements hook_theme()
function mymodule_theme( $existing, $type, $theme, $path ){
return [
'test-template' => [
'render element' => 'container', // To render a simple container element
'template' => 'test', // My template file name
'variables' => [
'test_var' => [] // Default value for my variable
]
]
];
}
And finally, my test template : templates/test.html.twig
<p>Hello !</p>
<!-- Just to see the content of my variable, after enabling twig debug mode -->
{{ dump(test_var) }}
Related doc or posts