get current url in twig template?

In symfony 2.1 you can use this:

{{ path(app.request.attributes.get('_route'), 
        app.request.attributes.get('_route_params')) }}

In symfony 2.0, one solution is to write a twig extension for this

public function getFunctions()
{
    return array(
        'my_router_params' => new \Twig_Function_Method($this, 'routerParams'),
    );
}

/**
 * Emulating the symfony 2.1.x $request->attributes->get('_route_params') feature.
 * Code based on PagerfantaBundle's twig extension.
 */
public function routerParams()
{
    $router = $this->container->get('router');
    $request = $this->container->get('request');

    $routeName = $request->attributes->get('_route');
    $routeParams = $request->query->all();
    foreach ($router->getRouteCollection()->get($routeName)->compile()->getVariables() as $variable) {
        $routeParams[$variable] = $request->attributes->get($variable);
    }

    return $routeParams;
}

And use like this

{{ path(app.request.attributes.get('_route'), my_router_params()|merge({'additional': 'value'}) }}

You won't need all this unless you want to add additional parameters to your links, like in a pager, or you want to change one of the parameters.


Get current url: {{ app.request.uri }} in Symfony 2.3, 3, 4, 5


Get path only: {{ app.request.pathinfo }} (without parameters)


Get request uri: {{ app.request.requesturi }} (with parameters)


{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

Tags:

Twig

Symfony