2014-09-30 93 views
2

我在學習Symfony 2,但是我遇到了一些問題。使用教程中,我創造了routing.yml裏面包這條路線:Symfony2路由不支持的密鑰

acme_demo_homepage: 
path:  /hello/{name} 
defaults: { _controller: AcmeDemoBundle:Default:index } 

random: 
path:  /random/{limit} 
defaults: { _controller: AcmeDemoBundle:Random:index } 

和Eclipse顯示我的行,其中defaults聲明錯誤,並且告訴我,:是意想不到的。

我創建了控制器:

<?php 
namespace Acme\DemoBundle\Controller; 
use Symfony\Component\HttpFoundation\Response; 

class RandomController 
{ 


public function indexAction($limit) 
{ 
    return new Response('<html><body>Number: '.rand(1, $limit).'</body></html>'); 
} 

} 

但是當我嘗試執行localhost/app_dev.php/random/10出現此錯誤:

路由文件「C:\ XAMPP \ htdocs中\ PROGETTI \的Symfony \ SRC \ Acme \ DemoBundle/Resources/config/routing.yml「包含」acme_demo_homepage「:」random「的不受支持的密鑰。預期的資源,類型,前綴,模式,路徑,主機,計劃,方法, 」。

+0

您的'routing.yml'是否與您發佈的路由一樣?你需要使用'path'和'defaults'鍵使用空格 – 2014-09-30 11:51:59

+0

是的,我的routing.yml就像我的發佈代碼,這是它的目錄路徑:Symfony \ src \ Acme \ DemoBundle \ Resources \ config \ routing.yml @TomaszMadeyski – 2014-09-30 11:58:12

回答

5

我覺得這一個缺口問題。從YAML規格:

在YAML塊樣式,結構由壓痕在 一個line.To保持可移植性的開始確定

在 一般,壓痕被定義爲一個零個或多個空格字符。 ,製表符不得縮進使用,因爲不同的系統治療的標籤是不同的。需要注意的是最現代的編輯器可以配置,使按下空格
適當數量的插入TAB鍵的結果。 「

所以:

acme_demo_homepage: 
    path:  /hello/{name} 
    defaults: { _controller: AcmeDemoBundle:Default:index } 

random: 
    path:  /random/{limit} 
    defaults: { _controller: AcmeDemoBundle:Random:index } 

或者您可以設置在PHP你的路由(這是我的偏好)。例如:

<?php 
//src/Acme/DemoBundle/Resources/config/routing.php 

use Symfony\Component\Routing\RouteCollection; 
use Symfony\Component\Routing\Route; 

$collection = new RouteCollection(); 

# main route 
$collection->add('_index', new Route('/dashboard/index/{page}/{year}/{month}', array(
    '_controller' => 'AcmeDashboardBundle:Default:index', 
    'page'  => 1, 
    'year'  => date('Y'), 
    'month'  => date('n'), 
))); 

return $collection; 
//end of file 
+0

好吧,現在在執行時沒有錯誤,應用程序可以正常工作,但我的Eclipse繼續向我顯示相同的錯誤@felipsmartins – 2014-09-30 12:04:32

+0

[Symfony Book](http://symfony.com/doc/current/book/routing。 HTML)有PHP路由的例子,但它仍然有很多不足之處。如果您想了解更多有關使用PHP進行路由的知識(而不是PHP註釋,YAML或XML),請參閱[路由組件參考](http://symfony.com/doc/current/components/routing/introduction.html #用法)。 – thohl 2016-01-12 17:45:27

+0

@thohl我認爲你已經評論了錯誤的地方,不是嗎? ^^ – felipsmartins 2016-01-12 17:52:37

0

請注意,縮進在YAML中至關重要。如果您的實際routing.yml看起來像您發佈的內容,則無法正確配置路由。以下是它的外觀:

acme_demo_homepage: 
    path:  /hello/{name} 
    defaults: { _controller: AcmeDemoBundle:Default:index } 

random: 
    path:  /random/{limit} 
    defaults: { _controller: AcmeDemoBundle:Random:index } 
0

看起來你的yml文件的格式是錯誤的。您需要介意yml文件中的空格(記住不要使用製表符而不是空格) - intendation定義了文件結構。

routing.yml文件應該

acme_demo_homepage: 
    path:  /hello/{name} 
    defaults: { _controller: AcmeDemoBundle:Default:index } 

random: 
    path:  /random/{limit} 
    defaults: { _controller: AcmeDemoBundle:Random:index }