2016-11-25 14 views
2

我是symfony框架的新手,所以我想在Php Storm中創建一個簡單的應用程序。我創建了一個新的LuckyController類,裏面有一個返回一個隨機數的函數,我添加了一個路由註釋。問題是我不知道如何根據路線運行它。如果我點擊運行 - > LuckyController它給了我一個空白頁。我已經盡力更改URL像瀏覽器:symfony顯示瀏覽器中的初始項目

http://localhost:8000/lucky/number 

,但它說:「這個網站無法訪問」或

http://localhost:63342/initSymfony/src/AppBundle/Controller/LuckyController/lucky/number 

在我的功能和一切,但它給了我「404未找到」。

我的代碼:

namespace AppBundle\Controller; 

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Component\HttpFoundation\Response; 

class LuckyController { 
/** 
* @Route("/lucky/number") 
*/ 
public function numberAction(){ 
    $number = rand(1,100); 
    return new Response(
     '<html><body>Lucky number: '.$number.'</body></html>' 
    ); 
} 
} 

如何解決這個問題?

回答

1

我不知道你的方式是否有效,但我總是這樣做。你試圖做的是將控制器顯示爲網頁,這就是你得到一個空視圖的原因(我不能確定是否這是爲什麼,從未嘗試過創建HTML頁面的方式):

return $this->render('tiwg/luckyNumber.html.twig', array(
      'luckyNumber' => $number 
//NOTE: Make sure the render matches the path where you place the file 
)); 

所以你要做的就是告訴控制器創建一個幸運數字,然後將該值發送給你渲染的twig.html文件。然後這可以使用以下要求

<div> 
    Your lucky number: {{luckynumber}} (containing the vairable) 
</div> 
+0

我解決它!我運行命令php bin/console server:運行,然後在瀏覽器localhost:8000/lucky/number謝謝 – johnwilliam25

相關問題