[ACCEPTED]-Twig templates engine: get current url-twig

Accepted answer
Score: 28

The following works in Silex and most certainly 2 in Symfony2 as they share the Request class 1 (I did not test though) :

{{ app.request.getRequestUri() }}
Score: 7

Finding the current URL

The current URL is supplied by your web 9 server and written to the $_SERVER super-global. Run 8 this small script, <?php echo '<pre>'; print_r($_SERVER);, through your server 7 and root around to find the value(s) you 6 are looking for.

Related questions on this 5 subject:

The PHP manual describes the nature of the available $_SERVER values here.

Getting the URL in TWIG

After you have the URL, you need 4 to pass it as a template variable when calling 3 render(...) on the Twig template instance. For example, you 2 might code this.

$current_url = // figure out what the current url is

// pass the current URL as a variable to the template
echo $template->render(array('current_url' => $current_url));

To use the variable in the 1 template, you use the {{ variable_name }} syntax.

Score: 4

Go http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Request.html

or : {{ app.request.getUri() }} for full Uri.

0

Score: 2

Keeping best practice in mind, at this time 5 you should use Symfony\Component\HttpFoundation\RequestStack.

See http://symfony.com/blog/new-in-symfony-2-4-the-request-stack.

As of Symfony 2.4, the 4 best practice is to never inject the request 3 service, but to inject the request_stack 2 service instead [...]

So in a Silex application 1 it could be achieved with :

app.request_stack.getCurrentRequest.getUri
Score: 0

Here something I found to make it generic 5 with the sliex Framework. I guess my solution 4 is not perfect but it's get the job done.

in 3 your PHP code add this code :

$app = new Silex\Application();
// add the current url to the app object.
$app['current_url'] = $_SERVER['REQUEST_URI'];

Then in your 2 Twig template you can do

{{ app.current_url }}

Let me know what 1 is the botom line of this method.

More Related questions