Php drupal 8使用控制器渲染模板细枝时出错
我试图用我的控制器呈现一个模板,但不起作用 它显示了以下错误: LogicException:控制器必须返回响应(Hello Bob!给定)。在Symfony\Component\HttpKernel\HttpKernel->handleRaw()中(core/vendor/Symfony/http kernel/Symfony/Component/HttpKernel/HttpKernel.php的第163行) 我的职能:Php drupal 8使用控制器渲染模板细枝时出错,php,symfony,drupal,drupal-8,Php,Symfony,Drupal,Drupal 8,我试图用我的控制器呈现一个模板,但不起作用 它显示了以下错误: LogicException:控制器必须返回响应(Hello Bob!给定)。在Symfony\Component\HttpKernel\HttpKernel->handleRaw()中(core/vendor/Symfony/http kernel/Symfony/Component/HttpKernel/HttpKernel.php的第163行) 我的职能: public function helloAction($name)
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));
}
在Drupal8中,可以从控制器返回响应对象或渲染数组。所以你有两个选择: 1) 将渲染模板放置到响应对象中:
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) 将渲染模板放置到渲染阵列中:
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,
);
}
您还可以在不使用自定义模板的情况下使用第二个选项,执行以下操作:
public function helloAction($name) {
$markup = "<p> Without custom Template</p>";
return array(
'#markup' => $markup,
);
}
公共函数helloAction($name){
$markup=“无自定义模板””;
返回数组(
“#markup”=>$markup,
);
}
在这个完整的示例中,要从controller通过依赖项注入渲染细枝,您需要返回一个响应对象,而不是模板生成的字符串<代码>返回新响应($template->render(array('name'=>$name))应该为您做这件事,尽管我不能确定,因为我只将模板组件作为Symfony框架的一部分使用。@Qoop它工作正常,因为还有AjaxResponse()用于AJAX请求-它扩展了Symfony的JsonResponse类,并首先通过
json\u encode()
运行输出。
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') ,
);
}
}