如何在Symfony2中使用DefaultController.php的单个方法调用多个页面?

时间:2014-07-07 13:24:51

标签: symfony

以下是我从一种方法调用一个页面的代码,但我想从一个方法调用多个页面。我想调用所有页面,例如'视频列表','联系来自cmsAction()的信息','业务描述'等。

namespace Atpl\FrontBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller {

    /**
     * @Route("/",name="atpl_front_index")
     * @Template()
     * */
    public function indexAction() {
        $name = "test";
        $data = array('name' => $name);
        return $this->render('AtplFrontBundle:Default:index.html.twig', $data);
    }

    /**
     * @Route("/cms/{page}",name="atpl_default_cms")
     * @Template()
     * */
    public function cmsAction($page) {

        $data = array('page' => $page);
        return $this->render('AtplFrontBundle:Default:cms.html.twig', $data);
    }

    /**
     * @Route("/dashboard/",name="atpl_default_dashboard")
     * @Template()
     * */
    public function dashAction() {

        $dash = "This is Dashboard.";
        $data = array('dash' => $dash);
        return $this->render('AtplFrontBundle:Default:dashboard.html.twig', $data);
    }

}

1 个答案:

答案 0 :(得分:0)

可以按照以下方式完成:

现在你需要两个动作:

第一个动作:

/**
 * @Route("/list",name="list")
 * @Template()
 * */
public function listAction() {
    $em = $this->getDoctrine()->getManager();

    $pagesData = $em->getRepository('YourBundle:TablePages')->findAll(); 

       return $this->render('YourBundle:Default:list.html.twig',array('pages' => $pagesData));
    } 
}

此处'TablePages'是您的实体类名称..

第二个动作:

/**
 * @Route("/{id}/pageShow",name="page_show")
 * @Template()
 * */
public function pageShowAction($id) {
    $em = $this->getDoctrine()->getManager();

    $pageData = $em->getRepository('YourBundle:TablePages')->find($id); 

       return $this->render('YourBundle:Default:show.html.twig',array('page' => $pageData));
    } 
}

现在你有两个枝条文件:

列出树枝:

 <!--src/YourBundle/Resources/views/Default/list.html.twig -->
 <! -- fetching the pages data listing -->
 {% page in pagesData %}
    <a href = "{{ path('page_show',{'id' : page.id }) }}">{{ page.yourTitleonNameField }}</a>
 {% endfor %}

此处'yourTitleonNameField'是您通过其识别页面的字段名称... 显示Twig:

<!--src/YourBundle/Resources/views/Default/show.html.twig -->
 <! -- showing the individual page -->
 {{ page.id }}
 {{ page.otherEntityAttributes }}
 ........

我希望它会对你有所帮助..