6

I've been googleing this question but I can't find anyone with my same problem... And I don't think I'm the only one here >.<

Let's see, I'm using translations in symfony2. I NEED to use twig for this... The thing is that I need 3 links so people can change the site's language. The link has to redirect to the same page the user is, but changing the '_locale'.

I first thought in something like this:

// in routing.yml
bundleStuff_someUrl:
    pattern:  /{_locale}/aloha
    defaults: { _controller: bundleStuff:Aloha:foo }

bundleStuff_fooUrl:
    pattern:  /{_locale}/foo/{fooParam}
    defaults: { _controller: bundleStuff:Foo:foo }

// in view.html.twig
<a href="{{ path((app.request.get('_route'), { '_locale': 'l1' }) }}">lang1</a>
<a href="{{ path((app.request.get('_route'), { '_locale': 'l2' }) }}">lang2</a>
<a href="{{ path((app.request.get('_route'), { '_locale': 'l3' }) }}">lang3</a>

The problem becomes when (in this case) the _route is fooUrl... Is there a way to append every attribute I have in the current view to the path I'm looking for? In other words referring to this example: is there a way so twig knows it has to add the 'fooParam' to the path if the current view is 'fooUrl'?

Thank's in advance! Hope this post is useful! :D

ThisIsErico
  • 1,885
  • 2
  • 19
  • 24

2 Answers2

11

_route_params request attribute holds the parameters of the current route. So the twig code would be,

{% set route = app.request.get('_route') %}
{% set route_params = app.request.get('_route_params') %}

<a href="{{ path(route, route_params | merge({ '_locale': 'l1' })) }}">lang1</a>
<a href="{{ path(route, route_params | merge({ '_locale': 'l2' })) }}">lang2</a>
<a href="{{ path(route, route_params | merge({ '_locale': 'l3' })) }}">lang3</a>
Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43
  • 1
    Notice that this _route_params attribute is only available in Symfony 2.1. If you use 2.0 you can use a custom twig extension as described here: http://htmlpurifier.org/docs/enduser-utf8.html – Carlos Granados Sep 12 '12 at 22:06
  • Sorry, wrong url. The right one is http://stackoverflow.com/questions/9378714/get-current-url-in-twig-template – Carlos Granados Sep 12 '12 at 22:18
  • Uo! Thank's to both of you! :D I'll try this at home and tell you what. Thx so much! – ThisIsErico Sep 13 '12 at 06:30
  • Ok, I had to do the twig extension since I'm using 2.0 (or 2.1 beta, not sure xD ). I got it running :D – ThisIsErico Sep 13 '12 at 20:18
1

For symfony 2.0 yo can get _locale variable in the controller and after send in a variable.

For example

Controller:

    $language = $this->getRequest()->get('_locale'); 
    $this->$this->redirect($this->generateUrl('bundleStuff_someUrl', array('language' => $language)))

and after in routing.yml

bundleStuff_someUrl: pattern: /{language}/aloha defaults: { _controller: bundleStuff:Aloha:foo }