如何在Symfony2 / Twig中正确生成模板中的URL

时间:2021-06-02 19:33:16

I'm working with Symfony2 and:

我正在使用Symfony2和:

I have this in the routing.yml

我在routing.yml中有这个

_welcome:
    resource: "@AcmeBundle/Controller/"
    type:     annotation

I this method within a controller:

我在控制器中的这个方法:

/**
 * @Route("/{page}")
 */
public function staticAction($page)
{
    return $this->render('AcmeBundle:Static:'.$page.'.html.twig');
}

To generate common pages:

要生成常用页面:

/home
/contact 
/privacy

But when I make the url on the menu:

但是当我在菜单上制作网址时:

<a href="{{ path('_welcome', {'page': 'home'}) }}">Home</a>
<a href="{{ path('_welcome', {'page': 'contact'}) }}">Contact</a>
<a href="{{ path('_welcome', {'page': 'privacy'}) }}">Privacy</a>

And I Symfony generates these urls:

而我Symfony生成这些网址:

…./?page=home
…./?page=contact
…./?page=privacy

And the right would be:

而权利将是:

/home
/contact
/privacy

What must I do?

我必须做什么?

1 个解决方案

#1


40  

You've to add a route name in your controller route annotations as follow,

您需要在控制器路由注释中添加路由名称,如下所示,

/**
 * @Route("/{page}", name="static")
 */
public function staticAction($page)
{
    // ... 
}

You could then call the twig path helper using that name,

然后,您可以使用该名称调用twig路径助手,

<a href="{{ path('static', {'page': 'home'}) }}">Home</a>

#1


40  

You've to add a route name in your controller route annotations as follow,

您需要在控制器路由注释中添加路由名称,如下所示,

/**
 * @Route("/{page}", name="static")
 */
public function staticAction($page)
{
    // ... 
}

You could then call the twig path helper using that name,

然后,您可以使用该名称调用twig路径助手,

<a href="{{ path('static', {'page': 'home'}) }}">Home</a>