关于 php:drupal 8 使用控制器渲染模板树枝的错误

drupal 8 error to render template twig with controller

我正在尝试使用我的控制器渲染模板但不起作用
它告诉我这个错误:

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).

我的功能:

1
2
3
4
5
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));
}


在 Drupal 8 中,您可以从控制器返回 Response 对象或渲染数组。所以你有两个选择:

1) 将渲染的模板放入一个 Response 对象中:

1
2
3
4
5
6
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) 将渲染后的模板放入渲染数组中:

1
2
3
4
5
6
7
8
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,
  );
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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') ,
    );
}
}

这个通过控制器的依赖注入渲染树枝的完整示例


你也可以使用没有自定义模板的第二个选项,这样做:

1
2
3
4
5
6
public function helloAction($name) {
  $markup ="<p> Without custom Template</p>";
  return array(
    '#markup' => $markup,
  );
}