I have created a custom Drupal 9 module, and I would like for this module to use different template files basing on a variable.
I have looked at hook_theme()
and I think the pattern return value might be what I am looking for, but I can't seem to make it work.
testpage.module
function testpage_theme() {
return array(
'testpage' => array(
'template' => 'testpage',
'variables' => array('items' => array(), 'title' => NULL),
'pattern' => 'testpage__'
)
);
}
### Controller file (Testpage.php)
```php
namespace Drupal\testpage\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;
class Testpage extends ControllerBase {
public function Render($name) {
$result = "Lorem ipsum";
$build = array(
'#theme' => array('testpage__'.$name, 'testpage'),
'#items' => $result,
'#title' => 'Testpage',
'#cache' => [
'max-age' => 0
]
);
return($build);
}
}
I created three template files in a "templates" folder.
- testpage.html.twig
- testpage--test.html.twig
- testpage--test2.html.twig
Basing on $name
, it should use the matching template file. However, it is always just using the markup from the testpage.html.twig. When $name
is equal to "test"
, it should use the testpage--test.html.twig file; when $name
is equal to "test2"
, it should use the testpage--test2.html.twig file. And it would be great if it would use the testpage.html.twig file as a fallback if a matching template does not exist.
I thought this was possible with the pattern return value, but I can't seem to get it to work correctly. Am I missing something, or is this not possible?