简体   繁体   English

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

[英]How Generating URLs from a template correctly in Symfony2/Twig

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? 我必须做什么?

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 path助手,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM