开发者

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' = a开发者_如何学Crray(
        '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?


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


If you want it with parameters use the following:

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜