【问题标题】:Forward with another template使用另一个模板转发
【发布时间】:2013-07-12 09:15:10
【问题描述】:

我遇到了 Symfony (v2.3) 的 forward 方法的问题。

基本上,我在两个不同的捆绑包中有两个控制器。假设DesktopBundle 代表应用程序的桌面版本,MobileBundle 代表移动版本。

我想将DesktopBundle 的动作代码重用到MobileBundle 的动作中。我现在做的是前锋:

桌面控制器

namespace Acme\DesktopBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * @Route("/")
 */
class IndexController extends Controller
{
    /**
     * @Route("", name="desktopIndex")
     * @Template()
     */
    public function indexAction()
    {
        /* some code I don't want to duplicate */

        return array(
            'some' => 'var'
        );
    }
}

移动控制器

namespace Acme\MobileBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * @Route("/")
 */
class IndexController extends Controller
{
    /**
     * @Route("", name="mobileIndex")
     * @Template()
     */
    public function indexAction()
    {
        return $this->forward('AcmeDesktopBundle:Index:index');
    }
}

现在它可以工作了,但显然 Response 对象与 indexAction 的桌面版本的渲染模板一起返回。

我想要的是获取变量然后渲染移动版本的模板。

我尝试将一个变量传递给 forward 方法,然后有条件地将动作渲染到桌面版本中:

return $this->forward(
    'acmeDesktopBundle:Index:index', 
    array('mobile' => true)
);

这可行,但我真的不想更改DesktopBundle 内的代码,而只想更改MobileBundle。有没有办法做到这一点?我遗漏了一些东西,还是应该采用完全不同的解决方案?

【问题讨论】:

    标签: php templates symfony


    【解决方案1】:

    转发意味着重定向到给定的页面,但不更改客户端上的 url。 IE。在服务器端重定向。如果您只想访问操作的返回值,只需调用它。使用@Template 注释,这变得非常容易。

    namespace Acme\MobileBundle\Controller;
    
    use Acme\DesktopBundle\Controller\IndexController as DesktopController;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
    
    /**
     * @Route("/")
     */
    class IndexController extends Controller
    {
        /**
         * @Route("", name="mobileIndex")
         * @Template()
         */
        public function indexAction()
        {
            $desktop = new DesktopController();
            $desktop->setContainer($this->container);
    
            $values = $desktop->indexAction();
            // do something with it
    
            return $values;
        }
    }
    

    【讨论】:

    • 是的,我试过这个,但我抛出了这个错误:FatalErrorException</abbr>: Error: Call to a member function get() on a non-object in /var/www/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php line 251
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 2020-09-09
    • 2012-07-05
    • 2012-08-11
    • 1970-01-01
    相关资源
    最近更新 更多