drupal 8 error to render template twig with controller

5.5k views Asked by At

I am trying to render a template with my controller but does not work it show me this error :

LogicException: The controller must return a response (

Hello Bob!

given). in Symfony\Component\HttpKernel\HttpKernel->handleRaw() (line 163 of core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php).

My function :

public function helloAction($name) {
$twigFilePath = drupal_get_path('module', 'acme') . '/templates/hello.html.twig';
$template = $this->twig->loadTemplate($twigFilePath);
return $template->render(array('name' => $name));
}
3

There are 3 answers

1
Alma On

In Drupal 8 you either return a Response object or a render array from a controller. So you have two options:

1) Place the rendered template into a Response object:

public function helloAction($name) {
  $twigFilePath = drupal_get_path('module', 'acme') . '/templates/hello.html.twig';
  $template = $this->twig->loadTemplate($twigFilePath);
  $markup = $template->render(array('name' => $name));
  return new Response($markup);
}

2) Place the rendered template into a render array:

public function helloAction($name) {
  $twigFilePath = drupal_get_path('module', 'acme') . '/templates/hello.html.twig';
  $template = $this->twig->loadTemplate($twigFilePath);
  $markup = $template->render(array('name' => $name));
  return array(
    '#markup' => $markup,
  );
}
0
Arito Melo On

Also you can Use the second option without custom template, doing this:

public function helloAction($name) {
  $markup = "<p> Without custom Template</p>";
  return array(
    '#markup' => $markup,
  );
}
0
Bafi On
class ClientController extends ControllerBase implements ContainerInjectionInterface ,ContainerAwareInterface {

protected $twig ;

public function __construct(\Twig_Environment $twig)
{
    $this->twig = $twig ;
}


public function index()
{

    $twigFilePath = drupal_get_path('module', 'client') . '/templates/index.html.twig';
    $template = $this->twig->loadTemplate($twigFilePath);
    $user = ['user' => 'name'] ; // as example
    $markup = [
        '#markup' => $template->render( ['users' => $users ,'kit_form' => $output] ),
        '#attached' => ['library' => ['client/index.custom']] ,
    ];
    return $markup;

}

// this is called first then call constructor 
public static function create(ContainerInterface $container)
{
    return new static(
        $container->get('twig') ,
    );
}
}

this full example to render twig by dependency injection from controller