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

UrlSymfonyBase Url

Url Problem Overview


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.

Url Solutions


Solution 1 - Url

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

Solution 2 - Url

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).

Solution 3 - Url

You can use the new request method getSchemeAndHttpHost():

{{ app.request.getSchemeAndHttpHost() }}

Solution 4 - Url

Valid from Symfony v2.1 through v6.0+

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/webapp/, then these two methods return these values:

getSchemeAndHttpHost

https://www.stackoverflow.com

getBaseUrl

/webapp

Note: getBaseUrl() includes the script filename (ie /app.php) if it's in your URL.

Solution 5 - Url

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

It can be fetched from controller like this:

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

Solution 6 - Url

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

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

Solution 7 - Url

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

or from controller

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

Solution 8 - Url

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

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

This creates an absolute url starting with /.

Solution 9 - Url

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.

Solution 10 - 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>

Solution 11 - Url

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

Solution 12 - Url

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

Solution 13 - Url

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.

Solution 14 - Url

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeoffrey De VylderView Question on Stackoverflow
Solution 1 - UrlcodecowboyView Answer on Stackoverflow
Solution 2 - UrlDamienView Answer on Stackoverflow
Solution 3 - UrlHugo NogueiraView Answer on Stackoverflow
Solution 4 - UrlMatt JanssenView Answer on Stackoverflow
Solution 5 - UrlsumanchalkiView Answer on Stackoverflow
Solution 6 - UrlMr. 14View Answer on Stackoverflow
Solution 7 - Urluser3869574View Answer on Stackoverflow
Solution 8 - UrlSashView Answer on Stackoverflow
Solution 9 - UrlArvidView Answer on Stackoverflow
Solution 10 - UrlSethunath K MView Answer on Stackoverflow
Solution 11 - UrlVladtnView Answer on Stackoverflow
Solution 12 - UrlIvan ProskuryakovView Answer on Stackoverflow
Solution 13 - UrlACJView Answer on Stackoverflow
Solution 14 - Urluser12531260View Answer on Stackoverflow