php 如何在 Symfony2/Twig 中正确地从模板生成 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15857358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:04:18  来源:igfitidea点击:

How Generating URLs from a template correctly in Symfony2/Twig

phpsymfonytwig

提问by rpayanm

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?

我必须做什么?

回答by Ahmed Siouani

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 pathhelper using that name,

然后你可以path使用这个名字调用树枝助手,

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