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

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

4 Comments

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: htmlpurifier.org/docs/enduser-utf8.html
Sorry, wrong url. The right one is stackoverflow.com/questions/9378714/…
Uo! Thank's to both of you! :D I'll try this at home and tell you what. Thx so much!
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
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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.