简体   繁体   中英

Symfony2 - Creating a URL

I've just started using Symfony. I want to echo the $bookid when I call a URL like book/5 , but I stuck somewhere.

Here's my DefaultController.php file

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');
    }
}

file: /Myproject/app/Resources/views/default/index2.html.php

<?php
echo $id;
?>

When I call the book/6 , I get a blank page. What's missing? Do I need to change somewhere else, too?

You should declare that variable in your action and pass it to your view.

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
        ));
    }
}

Whenever you have a parameter defined in your URL, you also need to "declare" it in your action function, so symfony maps it. Then, if you want to use it in your view, you have to pass it along.

If you are just starting with Symfony, I strongly recommend reading the Symfony Book and Cookbook. They are full of examples and relatively easy to understand, even for a newbie.

Other than that, the answer from smottt is correct. You add {id} in your route definition and receive it as parameter in your controller action.

Symfony book: Routing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM