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

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



相关讨论

  • 注意还有 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 )
{
    $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 ,
  ) ;
}

声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。