【问题标题】:FOSRestBundle: Pass additional variables to the Twig templateFOSRestBundle:将附加变量传递给 Twig 模板
【发布时间】:2012-09-09 13:49:51
【问题描述】:

我使用相同的操作来处理html 和json 响应,只是在后面的一条路由后缀.json。

json 工作没有问题,但是当响应为html 时,我需要将一个附加变量传递给Twig 模板,我不知道也找不到怎么做它。目前,我的代码是:

// $entity = get my data;

$name = 'foo';

$view = $this->view($entity, 200)
   ->setTemplate('MyBundle:MyController:myTemplate.html.twig')
   ->setTemplateVar('entity')
   ;

return $this->handleView($view);

如何将$name 传递给myTemplate.html.twig?我需要的是这样的:

//...
->setTemplate('MyBundle:MyController:myTemplate.html.twig', array('name' => $name))
//...

【问题讨论】:

    标签: php rest symfony fosrestbundle


    【解决方案1】:

    好的,我收到了打开issue in FosRestBundle github page 的回复。

    目前还没有直接的方法,但以下程序可以工作:

    1) 在路由默认值中分别添加带有html 和json 值的_format 选项:

    defaults: { _controller: myBundle:myController:myAction, _format: html } #or json
    

    2) 添加$_format作为动作签名的第一个参数:

    public function myActionAction($_format, $any_other_paramer)
    

    3) 有条件地向 Twig 模板添加更多变量:

    if ($this->get('fos_rest.view_handler')->isFormatTemplating($_format)) {
      $view->setData(array('name' => $name, 'entity' => $view->getData()));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      • 2017-11-10
      • 2019-04-03
      • 2011-05-08
      • 2015-08-24
      • 1970-01-01
      • 2019-04-03
      相关资源
      最近更新 更多