4

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

1 Answer 1

8

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.

my_module.module

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;
}

src/Controller/MyModuleController.php

public function index() {
  $build['#theme'] = 'template_name';
  //populate your build renderable array..
  return $build;
}
8
  • 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
    Commented Dec 1, 2015 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 ? Commented Dec 1, 2015 at 23:31
  • @Berdir - what do you mean by template is the default now?
    – EmGee
    Commented Dec 2, 2015 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
    Commented Dec 2, 2015 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
    Commented Dec 2, 2015 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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