【问题标题】:drupal 8 error to render template twig with controller使用控制器渲染模板树枝的 drupal 8 错误
【发布时间】:2015-06-13 10:10:57
【问题描述】:

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

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

你好 Bob!

给出)。在 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));
}

【问题讨论】:

  • 您需要返回一个响应对象,而不是模板生成的字符串。 return new Response($template->render(array('name' => $name))); 应该为你做,虽然我不能确定,因为我只使用了模板组件作为 Symfony 框架的一部分。
  • @Qoop 它的工作原理 thnks

标签: php symfony drupal drupal-8


【解决方案1】:

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

【讨论】:

  • 请注意,还有用于 AJAX 请求的 AjaxResponse() - 它扩展了 Symfony 的 JsonResponse 类并首先通过 json_encode() 运行输出。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    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') ,
        );
    }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多