Robert Martin
Robert Martin

Reputation: 17157

How do I access the Twig path() function from a Controller?

Okay, I know I can't literally call a twig template function from a controller, but to make links, I usually do the {{ path('_routeName') }} and that's great.

However, now I want to formulate some links in the controller that will then be passed to the template via parameters like this:

$params = array(
    'breadcrumbs' = array(
        'Donuts' => '/donuts',
        'Bearclaws' => '/donuts/bearclaws',
        'Strawberry bearclaw' => null,
    ),
);
return $this->render('Bundle:Donut:info.html.twig', $params);

Except I don't want to hard-code those links. What I'd like is to be able to do

        'Donuts' => path('_donutRoute'),

but how to reach the path method or equivalent?

Upvotes: 21

Views: 24822

Answers (3)

d.syph.3r
d.syph.3r

Reputation: 2215

If your controller is extending the Symfony2 Controller (Symfony\Bundle\FrameworkBundle\Controller\Controller) you can use the following to generate urls like this :

$this->generateUrl('_donutRoute')

Upvotes: 47

Imran Zahoor
Imran Zahoor

Reputation: 2787

If you want it with parameters use the following:

$this->generateUrl('_donutRoute', array('param1'=>'val1', 'param2'=>'val2'))

Upvotes: 13

Robert Martin
Robert Martin

Reputation: 17157

I found an alternative way to do this that I feel is equal to the one proposed by @d.syph.3r

The plan is to do:

'breadcrumbs' = array(
    'Donuts' => 'donutsRoute',
    'Bearclaws' => 'bearclawRoute',
    'Strawberry bearclaw' => null,
)

Then in the twig template, do:

{% for name, route in breadcrumbs %}
   {{ path(route) }}

The advantage here is that the Controller is not generating any HTML in this case.

Upvotes: 2

Related Questions