【发布时间】:2012-04-04 12:09:16
【问题描述】:
如何在我的模板中创建指向当前的链接?
我想创建一个语言切换器,它应该链接到各种语言的当前页面,所以所有参数都应该是相同的,除了语言环境。
【问题讨论】:
如何在我的模板中创建指向当前的链接?
我想创建一个语言切换器,它应该链接到各种语言的当前页面,所以所有参数都应该是相同的,除了语言环境。
【问题讨论】:
我最终为此滚动了自己的函数。我虽然起初它包含在FrameworkBundle 的某个地方,但没有找到任何关于它的信息。这是我采取的步骤。
首先,我创建了一个 Twig 扩展函数,该函数将输出与用户当前正在访问的路径相同的路径(包括参数和查询字符串)。我把这一步留给了你。如果您还不知道如何创建 Twig 扩展,您可以从 Symfony2 上的一个很好的教程中查看 this link 以了解如何创建 Twig 扩展。如果您需要,我可以帮助您。
下一步是创建将切换当前路由的语言环境的函数本身。此函数将需要 Request 和 Router 对象作为依赖项。就我个人而言,我将此功能放在名为RoutingHelper 的专用服务中。然后,我的 Twig 扩展功能会使用此服务。这里是我添加到依赖容器中的服务定义:
acme.helper.routing:
class: Application\AcmeBundle\Helper\RoutingHelper
scope: "request"
arguments:
request: "@request"
router: "@router"
还有我的服务的构造函数:
protected $request;
protected $router;
public function __construct($request, $router)
{
$this->request = $request;
$this->router = $router;
}
$locale 参数是要切换到的新语言环境。这里的功能:
public function localizeCurrentRoute($locale)
{
$attributes = $this->request->attributes->all();
$query = $this->request->query->all();
$route = $attributes['_route'];
# This will add query parameters to attributes and filter out attributes starting with _
$attributes = array_merge($query, $this->filterPrivateKeys($attributes));
$attributes['_locale'] = $locale;
return $this->router->generate($route, $attributes);
}
本质上,它完成了其他人迄今为止所做的工作,但它也处理参数和查询字符串。 filterPrivateKeys 方法将从路由属性中删除私有属性。这些属性是以下划线开头的属性,不应传递回路由生成器。这里是它的定义:
private function filterPrivateKeys($attributes)
{
$filteredAttributes = array();
foreach ($attributes as $key => $value) {
if (!empty($key) && $key[0] != '_') {
$filteredAttributes[$key] = $value;
}
}
return $filteredAttributes;
}
最后,我可以在我的 Twig 视图中创建链接以切换语言环境:
{% block language_bar %}
<a href="{{ localize_route('en') }}"> English </a>
<a href="{{ localize_route('fr') }}"> Français </a>
{% endblock %}
编辑:
这是我的树枝扩展服务定义:
acme.twig.extension:
class: Application\AcmeBundle\Twig\Extension\AcmeExtension
arguments:
container: "@service_container"
tags:
- { name: twig.extension }
在树枝扩展函数中我有这个调用:$routingHelper = $this->container->get('acme.helper.routing');
这应该解决由于树枝扩展不在请求范围内而发生的范围扩大异常。
更新:
现在可以使用 Symfony 2.1 以比以前更简单的方式拥有语言环境切换器。事实上,Symfony 的 2.1 版本引入了一个新的路由参数,使进行区域切换器更加变得容易。这里是代码,全部在twig中
{% set route_params = app.request.attributes.get('_route_params') %}
{# merge the query string params if you want to keep them when switching the locale #}
{% set route_params = route_params|merge(app.request.query.all) %}
{# merge the additional params you want to change #}
{% set route_params = route_params|merge({'_locale': 'fr'}) %}
{{ path(app.request.attributes.get('_route'), route_params) }}
它仍然是几行 twig 代码,但可以包含在 Twig 块中以便于重用。来自 Symfony 社区的 stof 对上述代码的感谢。
希望这是您正在寻找的。p>
问候,
马特
【讨论】:
<a href="{{ path(app.request.attributes.get('_route')) }}">Current page</a>
【讨论】:
<a href="{{ path(app.request.get('_route'), {'_locale': 'en'}) }}">English</a>
【讨论】: