[url] Getting the base url of the website and globally passing it to twig in Symfony 2

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.

This question is related to url symfony base-url

The answer is


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.


 <base href="{{ app.request.getSchemeAndHttpHost() }}"/>

or from controller

$this->container->get('router')->getContext()->getSchemeAndHttpHost()

This is now available for free in twig templates (tested on sf2 version 2.0.14)

{{ app.request.getBaseURL() }}

In later Symfony versions (tested on 2.5), try :

{{ app.request.getSchemeAndHttpHost() }}

Also for js/css/image urls there's handy function asset()

<img src="{{ asset('image/logo.png') }}"/>

This creates an absolute url starting with /.


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.


You can use the new request method getSchemeAndHttpHost():

{{ app.request.getSchemeAndHttpHost() }}

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.


Base url is defined inside Symfony\Component\Routing\RequestContext.

It can be fetched from controller like this:

$this->container->get('router')->getContext()->getBaseUrl()

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>

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

{{ dump(app.request.server.get('DOCUMENT_ROOT')) }}

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.


For Symfony 2.3+, to get the base url in a controller should be

$this->get('request')->getSchemeAndHttpHost();

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to symfony

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2 The CSRF token is invalid. Please try to resubmit the form What is the difference between .yaml and .yml extension? How can I use break or continue within for loop in Twig template? Running Composer returns: "Could not open input file: composer.phar" Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings Symfony - generate url with parameter in controller Call PHP function from Twig template

Examples related to base-url

Laravel: Get base url How to get base URL in Web API controller? How get the base URL via context path in JSF? Getting the base url of the website and globally passing it to twig in Symfony 2 How to get domain URL and application name?