1

我正在尝试使用我的控制器呈现模板,但它不起作用,它向我显示此错误:

LogicException:控制器必须返回响应(

你好鲍勃!

给定)。在 Symfony\Component\HttpKernel\HttpKernel->handleRaw() (core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php 的第 163 行)。

我的功能:

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

3 回答 3

3

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

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

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,
  );
}
于 2015-06-15T00:58:36.020 回答
0

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

public function helloAction($name) {
  $markup = "<p> Without custom Template</p>";
  return array(
    '#markup' => $markup,
  );
}
于 2015-07-17T14:54:33.403 回答
0
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') ,
    );
}
}

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

于 2015-12-07T14:32:44.277 回答