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)); } |
- 您需要返回一个响应对象,而不是模板生成的字符串。 return new Response($template->render(array(‘name’ => $name))); 应该为你做,虽然我不能确定,因为我只使用了模板组件作为 Symfony 框架的一部分。
- @Qoop 它的工作原理
在 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 |
- 注意还有 AjaxResponse() 用于 AJAX 请求 – 它扩展了 Symfony 的 JsonResponse 类并首先通过 json_encode() 运行输出。
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)
public function index() $twigFilePath = drupal_get_path(‘module’, ‘client’) . ‘/templates/index.html.twig’; } // this is called first then call constructor |
这个通过控制器的依赖注入渲染树枝的完整示例
你也可以使用没有自定义模板的第二个选项,这样做:
1
2 3 4 5 6 |
public function helloAction($name) {
$markup =“<p> Without custom Template</p>”; return array( ‘#markup’ => $markup, ); } |
来源:https://www.codenong.com/30817470/