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>
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.
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;
}
}
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.