如何在Symfony2/Twig中从模板正确生成URL [英] How Generating URLs from a template correctly in Symfony2/Twig

查看:72
本文介绍了如何在Symfony2/Twig中从模板正确生成URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Symfony2和:

I'm working with Symfony2 and:

我在routing.yml中有这个

I have this in the 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');
}

要生成通用页面:

/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>

而我Symfony会生成以下网址:

And I Symfony generates these urls:

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

正确的是:

/home
/contact
/privacy

我该怎么办?

推荐答案

您必须按如下所示在控制器路线注释中添加路线名称,

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

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

然后您可以使用该名称调用树枝path助手,

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

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

这篇关于如何在Symfony2/Twig中从模板正确生成URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆