I'm making the switch from CodeIgniter to Symfony 2. Can someone please give me an example of how to:
- Get the base url (the url without the route specific parts)
- Globally pass this variable to the twig bundle so I can use it in every template.
I'm making the switch from CodeIgniter to Symfony 2. Can someone please give me an example of how to:
Why do you need to get this root url ? Can't you generate directly absolute URL's ?
{{ url('_demo_hello', { 'name': 'Thomas' }) }}
This Twig code will generate the full http:// url to the _demo_hello route.
In fact, getting the base url of the website is only getting the full url of the homepage route :
{{ url('homepage') }}
(homepage, or whatever you call it in your routing file).
Valid from Symfony v2.1 through v4.1+
If you want the base URL to a Symfony application, you should use getSchemeAndHttpHost()
concatenated together with getBaseUrl()
, similar to how getUri()
works, except without the router path and query string.
{{ app.request.schemeAndHttpHost ~ app.request.baseUrl }}
For example, if your Symfony website URL lives at https://www.stackoverflow.com/app1/
, then these two methods return these values:
getSchemeAndHttpHost
https://www.stackoverflow.com
getBaseUrl
/app1
Note: getBaseUrl()
includes the script filename (ie /app.php
) if it's in your URL.
Instead of passing variable to template globally, you can define a base template and render the 'global part' in it. The base template can be inherited.
Example of rendering template From the symfony Documentation:
<div id="sidebar">
{% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}
</div>
For current Symfony version (as of writing this answer it's Symfony 4.1) do not directly access the service container as done in some of the other answers.
Instead (unless you don't use the standard services configuration), inject the request object by type-hinting.
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* The YourService class provides a method for retrieving the base URL.
*
* @package App\Service
*/
class YourService
{
/**
* @var string
*/
protected $baseUrl;
/**
* YourService constructor.
*
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->baseUrl = $requestStack->getCurrentRequest()->getSchemeAndHttpHost();
}
/**
* Returns the current base URL.
*
* @return string
*/
public function getBaseUrl(): string
{
return $this->baseUrl;
}
}
See also official Symfony docs about how to retrieve the current request object.
In Symfony 5 and in the common situation of a controller method use the injected Request object:
public function controllerFunction(Request $request, LoggerInterface $logger)
...
$scheme = $request->getSchemeAndHttpHost();
$logger->info('Domain is: ' . $scheme);
...
//prepare to render
$retarray = array(
...
'scheme' => $scheme,
...
);
return $this->render('Template.html.twig', $retarray);
}