Symfony2注释无法为命名路由生成URL

时间:2014-01-16 21:22:19

标签: php symfony routing annotations

就我搜索过的类似问题而言,我找不到解决问题的方法。

这是app / config / routing.yml中的条目:

basym_address:
    resource: "@BasymAddressBundle/Controller/"
    type:     annotation
    prefix:   /

这是相应的控制器:

namespace Basym\AddressBundle\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
 *
 * @package Basym\AddressBundle\Controller
 *
 * @Route("/address")
 */
class DefaultController extends Controller
{
    /**
     * @Route("/{name}", defaults={"name" = "Christian Lauer"})
     * @Method({"GET", "POST"})
     * @Template()
     */
    public function indexAction($name = "Christian Lauer")
    {
        return array('name');
    }
}

以下是抛出异常的代码(来自MenuBuilder):

        $menu->addChild('Home', array('route' => 'address'));

这是app / console路由器的输出:match / address:

> php.exe app\console router:match /address
Route "basym_address_default_index" matches

[router] Route "basym_address_default_index"
Name         basym_address_default_index
Path         /address/{name}
Host         ANY
Scheme       ANY
Method       GET|POST
Class        Symfony\Component\Routing\Route
Defaults     _controller: BasymAddressBundle:Default:index
             name: Christian Lauer
Requirements 
Options      compiler_class: Symfony\Component\Routing\RouteCompiler
Path-Regex   #^/address(?:/(?P<name>[^/]++))?$#s

调用MenuBuilder的twig部分看起来像这样(第19行:

{{ knp_menu_render('BasymSystemBundle:MenuBuilder:mainMenu') }}

我得到“在渲染模板期间抛出异常(”无法生成指定路径的URL“地址”因为这样的路径不存在。“)在kernel.root_dir / Resources / views / layout中第19行的.html.twig“。为什么呢?

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:0)

只能使用指向函数的路径。你只有一条工作路线。它是/ address / {name}

/ address仅引用控制器类DefaultController

以下代码将支持路由/地址:

namespace Basym\AddressBundle\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
 *
 * @package Basym\AddressBundle\Controller
 *
 * @Route("/address")
 */
class DefaultController extends Controller
{
    /**
     * @Route("/{name}", defaults={"name" = "Christian Lauer"})
     * @Method({"GET", "POST"})
     * @Template()
     */
    public function indexAction($name = "Christian Lauer")
    {
        return array('name');
    }

    /**
     * @Route("/")
     * @Method({"GET", "POST"})
     */
    public function anotherAction()
    {
        return new Response();
    }
}

答案 1 :(得分:0)

我认为您应该使用basym_address_default_index作为路线名称,而不是address