简体   繁体   中英

"Unable to generate a URL for the named route

Ive just started playing with symfony2 and im working on adding url etc. I cant seem to get my twig template to pick up on my function when passed its name using @Route. Any ideas why?

Controller:

/**
* @Route("/cube/{number}", name="get_cubed")
*/
public function indexAction($number)
{
    $cube = $number * $number * $number;
    return $this->render('NumberCubedBundle:Default:index.html.twig',
        array('number' => $number, 'cube' => $cube)
    );
}

My Twig File:

{% extends '::base.html.twig' %}
{% block title %}Cube Number Generator{% endblock %}
{% block body %}
    {{ number }}^3 = {{ cube }}
    <a href="{{ path('get_cubed', { 'number': 40 }) }}">Cube 40</a>
{% endblock %}

The Error:

An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "get_cubed" as such route does not exist.") in NumberCubedBundle:Default:index.html.twig at line 5. 

Any help would be massively appreciated. Thanks

EDIT: why the annotation didn't work

Most probably you didn't include Sensio's vendor bundle as explained in annotation routing and sensio framwork EXTRA bundle .

The default routing mechanism uses the routing file (routing.yml) which does not need the extra bundle.

The routing through annotations, on the other hand, are considered an additional feature that is not always desired and thus has been extracted to a separate and optional bundle.


You need to configure the route in the routing file:

app/config/routing.yml

Define the route get_cubed using the standard Symfony 2 routing syntax .

Much like this:

get_cubed:
    path:      /cube/{number}
    defaults:  { _controller: NumberCubedBundle:Default:index }
    requirements:
        number: \d+

Now you should be able to get the page with the route:

.../app_dev.php/cube/40

The Solution for pattern annotation is: on app/config/routing.yml add :

tuto_produit_bundle:
    resource: "@ProduitBundle/Controller/"
    type: annotation
    prefix: /cat

and o URL:

http://localhost/produits/Symfony/web/app_dev.php/cat/{adresse}/{route action}
like http://localhost/vente%20produits/Symfony/web/app_dev.php/cat/categorie/

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