我在Symfony2中的路由有问题。
事实上,我下载了最新版本,并在我的服务器上运行它。演示效果良好。
现在我想做以下事情:我想创建一个TestController,这个控制器应该有:
- 索引视图
- 类似hello世界的景色
- 我可以传递2个参数的视图
因此,我开始在src'Acme'DemoBundle'Controller
文件夹中创建一个名为TestController
的新控制器。这是代码:
<?php
namespace Acme'DemoBundle'Controller;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use Symfony'Component'HttpFoundation'RedirectResponse;
use Acme'DemoBundle'Form'ContactType;
// these import the "@Route" and "@Template" annotations
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Route;
use Sensio'Bundle'FrameworkExtraBundle'Configuration'Template;
class TestController extends Controller
{
public function indexAction()
{
return array();
}
public function hello2Action($name1, $name2)
{
return array();
}
public function helloAction()
{
return array();
}
}
然后,我在一个名为hello.html.twig
、index.html.twig
和hello2.html.twig
的新文件夹src'Acme'DemoBundle'Resources'views'Test
中创建了3个视图
他们两个都有类似的内容
{% extends "AcmeDemoBundle::layout.html.twig" %}
{% block title "Symfony - Demos" %}
{% block content_header '' %}
{% block content %}
foo!!!
{% endblock %}
最后,我编辑了routing.dev.yml
,并添加了一些类似的内容:
_name1:
resource: "@AcmeDemoBundle/Controller/TestController.php"
type: annotation
prefix: /test
_name2:
resource: "@AcmeDemoBundle/Controller/TestController.php"
type: annotation
prefix: /test/hello
_name3:
resource: "@AcmeDemoBundle/Controller/TestController.php"
type: annotation
prefix: /test/hello2/{name1}&{name2}
当我想运行测试控制器时,我得到:
未找到"GET/test/"的路由
怎么了?是否可以为两个控制器功能提供一个视图?(像hello()和hello($foo))?
您也可以这样做:
-
在routing_dev.yml中,确保您有以下内容:
_main: resource: routing.yml
-
在routing.yml中,添加如下内容:
AcmeDemoBundle: resource: "@AcmeDemoBundle/Resources/config/routing.yml" prefix: /test
您可以在访问该特定捆绑包时选择所需的前缀。
-
在Acme/DemoBundle/Resources/config/routing.yml中,您现在可以添加您的路由模式。
name1: pattern: / defaults: { _controller: AcmeDemoBundle:Test:index } name2: pattern: /hello defaults: { _controller: AcmeDemoBundle:Test:hello } name3: pattern: /hello2/{name1}/{name2} defaults: { _controller: AcmeDemoBundle:Test:hello2 }
现在,您可以访问、路由/test、%test/hello和''test/hello2/firstname/lastname'。这只是symfony 2中管理路由的一种方法。这可能会有所帮助:http://symfony.com/doc/current/book/routing.html
两件事:
-
您已经为"/test"定义了路由,但没有为"/test/"定义路由,这就是为什么您收到了第一条错误消息(找不到"GET/test/"的路由)。在任何情况下,最好将路线定义为另一个答案中建议的注释。
-
为了让控制器使用您正在使用的结构(返回和变量数组,在本例中为空数组),您需要用"@Template"注释来标记它们,如下所示:
/*
* @Route("/hello/{name}", name="_demo_hello") * @Template() */ public function helloAction($name)
这使Symfony能够自动查找相应的模板文件。如果您不这样做,您需要返回一个Response对象,指示应该渲染的模板,类似于以下内容:
return $this->render('AcmeDemoBundle:Test:index.html.twig');
在路由中,您定义了前缀,但实际上并没有定义路由。由于您使用的是注释,因此必须通过控制器中的注释来定义路由。
请参阅这本伟大的手册;)
你的routing_dev.yml
应该是这样的:
_name1:
resource: "@AcmeDemoBundle/Controller/TestController.php"
type: annotation
在你的控制器中,你应该为每个动作定义@Route:
/**
* @Route("/hello")
*/
public function helloAction()
{
return array();
}
在此之后,您将能够通过路线/hello
等访问您的行动。
干杯;)