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:
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);
}
In one situation involving a multi-domain application, app.request.getHttpHost helped me out. It returns something like example.com or subdomain.example.com (or example.com:8000 when the port is not standard). This was in Symfony 3.4.
I tried all the options here but they didnt work for me. Eventually I got it working using
{{ site.url }}
Hope this helps someone who is still struggling.