smartius
smartius

Reputation: 653

How to get current absolute url in twig without rendering route?

In twig I need to get the current full uri (url + uri ) without render it it like

path('route_test', {param1:1})

How to get it ?

Upvotes: 15

Views: 20414

Answers (4)

Larzan
Larzan

Reputation: 9677

As it was said above, some of the answers are not valid anymore.

What worked for me as of 2017'09 is this

{{ url('<current>') }}

Upvotes: 5

Pierrickouw
Pierrickouw

Reputation: 4704

Try to use :

{{ app.request.uri }}

Upvotes: 44

Alain
Alain

Reputation: 36954

You may have issues with subrequests ($this->forward from a controller or {{ render(controller('...')) }} from a view), I prefer using a Twig extension for this.

<?php

namespace AppBundle\Twig\Extension;

// ...    

class MyExtension extends \Twig_Extension
{
    // ...

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('current_locale', [$this, 'currentLocale']),
            new \Twig_SimpleFunction('current_uri', [$this, 'currentUri']),
        ];
    }

    public function currentLocale()
    {
        return $this->get('request_stack')->getMasterRequest()->getLocale();
    }

    public function currentUri()
    {
        return $this->get('request_stack')->getMasterRequest()->getUri();
    }

    public function getName()
    {
        return 'my';
    }
}

Upvotes: 1

Andrei123
Andrei123

Reputation: 21

In latest version of twig is not work anymore {{app.request.uri}}

Try {{global.request.uri}} instead.

Upvotes: 2

Related Questions