31

Is there any facility to generate a path for a given route and arguments, appending the query string automatically? As a temporary workaround i'm using a self made macro:

{% macro path(route, args, with_query) %}
{% spaceless %}
    {% set with_query = with_query|default(false) and app.request.queryString %}
    {{ path(route, args) ~ (with_query ? '?' ~ app.request.queryString : '' ) }}
{% endspaceless %}
{% endmacro %}

Is there some native function in Symfony2/Twig for doing this?

2 Answers 2

102

A nice thing with path Twig extension is that unknow parameters passed through the args array are automatically appended at the end of the URL as GET paramaters :

{{ path('route_id', {'routeParam':'foo', 'unknownParam':'bar'}) }}

will produce

/path/to/route/foo?unknownParam=bar

Sign up to request clarification or add additional context in comments.

6 Comments

Well, answer accepted, even if i need it more dynamic (i.e. unknownParam are more and not fixed).
this is just a sample, you can put a variable for ''unknownParam'' and ''bar'' !
This 'unknown parameters' functionality is part of the core Symfony2 router - so you can use the same approach in your controllers. From the official documentation: $router->generate('blog', array('page' => 2, 'category' => 'Symfony')); // /blog/2?category=Symfony
The parenthesis is slightly wrong. Should be: {{ path('route_id', {'routeParam':'foo', 'unknownParam':'bar'}) }}
Is there a possibility to produce /path/to/route/foo?unknownParam (without = sign)? I tried {{ path('route_id', {'routeParam':'foo', 'unknownParam':''}) }} but it generates /path/to/route/foo?unknownParam=
|
6

As simple as :

{{ path('route_id', app.request.query.all) }}

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.