I want to render a custom template in a module controller but I don't know how. How do I achieve this?


You need to let Drupal know about the theme, and then you can leverage it in the controller code. The template needs to be in the folder my_module/templates.


function my_module_theme() {
  $theme['template_name'] = [
    'render element' => 'build',
    'template' => 'template_file_name',//This is only needed if you need a different template file name than the array key above, 'template_name'.

  //override existing template for this module
  $theme['html__my_module__template_file_name'] = [
    'template' => 'html--my_module--template_file_name',
  return $theme;


public function index() {
  $build['#theme'] = 'template_name';
  //populate your build renderable array..
  return $build;
| improve this answer | |
  • Correct but the more common use case is variables, would be good to adapt that and e.g. include a variable and also how to specifically set it in the render array. Also, template is the default now in 8.x and no longer need to specified explicitly. – Berdir Dec 1 '15 at 22:43
  • Great! the content of the populate is displayed in the Bartik theme, how about if I want the template content to be displayed without to extend the Bartik theme ? – Lhassan Baazzi Dec 1 '15 at 23:31
  • @Berdir - what do you mean by template is the default now? – EmGee Dec 2 '15 at 14:13
  • 1
    @blakphyre Drupal 7 automatically assumed a theme function with the same name if you did not specificy a template key. Drupal 8 automatically assumes a template with the same name(with _ => -, so template_name becomes template-name.html.twig) unless you specificy the function key explicitly. – Berdir Dec 2 '15 at 14:46
  • 1
    @Berdir I see what you're saying, I'll amend my answer to show that - I'm not sure about other other part, including a variable and passing it through the render array. I haven't done that yet myself. – EmGee Dec 2 '15 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.