Symfony 2 equivalent for url_for () function in symfony 1

In Symfony 1, we can access the action on the template page, for example, url_for('modulename/actionname') , without writing anything to routing.yml.

How is this possible in Symfony2 ?, that is, if I need to access several actions in a branch without specifying routing. This is useful when using ajax.

Thanks in advance

+6
source share
2 answers

If I understand your question correctly, you are asking how to create a URL by passing the module name and action name instead of the route name. It is right?

I do not think this is possible in Symfony2. If you look at the generate method in Symfony\Component\Routing\Generator\UrlGenerator , you will see that it expects the name of the route as the first parameter. In addition, Symfony2 does not support the main routes that symfony 1 runs (see below for reference).

 default_index: url: /:module param: { action: index } default: url: /:module/:action/* 

Without these shared routes, you cannot simply access / myModule / myAction without actually defining a route for it. And don't forget that Symfony2 now uses packages, which would complicate this further.

So, for any actions that you want to access, you need to write routes for them.

To really generate urls ...
- From the controller: $this->generateUrl($routeName);
- From the PHP template: $view['router']->generate($routeName);
- From the Twig pattern: {{ path('_routeName') }} or {{ url('_routeName') }} for an absolute URL

+3
source

In addition to the words Arms', here are a few examples (with parameters):

Say our routing:

 #routing.yml acme_demo_page: path: /{page}.{_format} defaults: _controller: AcmeDemoBundle:Page:index 

We will create the URL for this routing as shown below:

From any controller action:

 $url = $view['router']->generate("acme_demo_page", array( "page" => "main", "_format" => "html", )); 

From any PHP template:

 $url = $this->generateUrl("acme_demo_page", array( "page" => "main", "_format" => "html", )); 

From any Twig template:

 <a href="{{ path('acme_demo_page', {page:'main', _format:'html'}) }}">Home</a> <a href="{{ url('acme_demo_page', {page:'main', _format:'html'}) }}">Abs Home</a> 


Hope this helps. Greetings.

+1
source

Source: https://habr.com/ru/post/900761/


All Articles