[英]Symfony2 - Creating a URL
我剛剛開始使用Symfony。 當我調用諸如book / 5之類的URL時,我想回顯$ bookid,但是我卡在某個地方。
這是我的DefaultController.php文件
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller {
/**
* @Route("/book/{id}", name="book")
*/
public function indexAction() {
return $this->render('default/index2.html.php');
}
}
文件:/Myproject/app/Resources/views/default/index2.html.php
<?php
echo $id;
?>
當我把這本書叫做6時,我得到了一個空白頁。 缺少了什么? 我也需要在其他地方更改嗎?
您應該在操作中聲明該變量並將其傳遞給視圖。
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
/**
* @Route("/book/{id}", name="book")
*/
public function indexAction($id)
{
return $this->render('default/index2.html.php', array(
'id' => $id
));
}
}
只要在URL中定義了參數,就還需要在操作函數中“聲明”該參數,因此symfony會對其進行映射。 然后,如果要在視圖中使用它,則必須將其傳遞。
如果您剛開始使用Symfony,我強烈建議您閱讀Symfony Book和Cookbook。 它們充滿了示例,相對來說也比較容易理解,即使對於新手也是如此。
除此之外,smottt的答案是正確的。 您在路由定義中添加{id},並在控制器操作中將其作為參數接收。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.