Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig templates engine: get current url

Tags:

php

twig

How can I get the current URL from a Twig template?

I am using Twig with PHP, without any other framework.

like image 533
nKognito Avatar asked Feb 18 '12 07:02

nKognito


People also ask

How do I get the current URL in twig?

You can get the current URL in Twig/Silex 2 like this: global. request. attributes. get('_route') .

Is twig a template engine?

Twig is a template engine for the PHP programming language.


3 Answers

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

{{ app.request.getRequestUri() }}
like image 92
neemzy Avatar answered Sep 20 '22 19:09

neemzy


Finding the current URL

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

Related questions on this subject:

  • getting current URL
  • PHP Determining the current url
  • How to get URL of current page in PHP

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

Getting the URL in TWIG

After you have the URL, you need to pass it as a template variable when calling render(...) on the Twig template instance. For example, you 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 template, you use the {{ variable_name }} syntax.

  • Developer's basic Twig documentation
  • Twig designer documentation for using variables.
like image 28
erisco Avatar answered Sep 23 '22 19:09

erisco


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

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

like image 34
Breith Avatar answered Sep 21 '22 19:09

Breith