Symfony 2 在控制器中调用一个函数(带有 temlate 渲染)


Symfony 2 Call a function(with temlate render) in a Controller

我的控制器中有两个简单的函数:

    public function indexAction(){
    $userid = $this->getUser()->getId();
    $userdata = $this->getDoctrine()
            ->getRepository('LiveupUserBundle:userData')
            ->findOneById($userid);
    $userfriends = $this->getDoctrine()
            ->getRepository('LiveupUserBundle:userFriends')
            ->findByUser($userid);
    return $this->render('LiveupMainBundle:Main:profile.html.twig', array(
        'userdata' => $userdata,
        'userfriends' => $userfriends
    ));
}

    public function peopleAction($nick){
    if($nick){
        $frienddata = $this->getDoctrine()
                ->getRepository('LiveupUserBundle:userData')
                ->findOneByNick($nick);
        if($frienddata->getId() === $this->getUser()->getId())
        {
            self::indexAction();
        }else{
            $friendfriends = $this->getDoctrine()
                    ->getRepository('LiveupUserBundle:userFriends')
                    ->findByUser($frienddata->getId());
            return $this->render('LiveupMainBundle:Main:people_profile.html.twig', array(
                'frienddata' => $frienddata,
                'friendfriends' => $friendfriends
            ));
        }
    }
}

问题是,如果第二个函数中的语句为真,我想从该函数(profile.html.twig)执行 indexAction 并呈现模板,但我没有得到响应错误。谁能帮我?提前谢谢。

我认为您正在寻找的是转发请求。 从文档中,您可以执行以下操作:

public function peopleAction($nick){
    if($nick){
        $frienddata = $this->getDoctrine()
            ->getRepository('LiveupUserBundle:userData')
            ->findOneByNick($nick);
        if($frienddata->getId() === $this->getUser()->getId())
        {
            $response = $this->forward('AppBundle:Something:index', array(
                 'var1'  => $anyVar //if you need to forward a param
            ));
        }else{
            $friendfriends = $this->getDoctrine()
                ->getRepository('LiveupUserBundle:userFriends')
                ->findByUser($frienddata->getId());
            $response = $this->render('LiveupMainBundle:Main:people_profile.html.twig', array(
                'frienddata' => $frienddata,
                'friendfriends' => $friendfriends
            ));
        }
        return $response;
    }
}

此外,通过查看代码,如果 $nick 变量的计算结果为 false,您仍会收到错误,因为不会返回任何响应。 您应该确保始终返回来自控制器的响应。

要考虑的另一件事是,也许重定向也可以满足您的需求。 查看文档以了解如何做到这一点,从控制器来看非常简单。

你忘了return语句:

return self::indexAction();

此外,如果nick可以为空,则应处理这种情况并引发异常或返回响应。