Obtener la url base del sitio web y pasarla globalmente a twig en Symfony 2


Estoy haciendo el cambio de CodeIgniter a Symfony 2. ¿Puede alguien por favor darme un ejemplo de cómo:

  • Obtener la url base (la url sin las partes específicas de la ruta)
  • Pase globalmente esta variable al paquete twig para que pueda usarla en cada plantilla.
Author: Habeeb Perwad, 2011-07-27

11 answers

¿Por qué necesita obtener esta url raíz ? ¿No puedes generar directamente URL absolutas?

{{ url('_demo_hello', { 'name': 'Thomas' }) }}

Este código Twig generará la url http:// completa a la ruta _demo_hello.

De hecho, obtener la url base del sitio web solo es obtener la url completa de la ruta de la página de inicio:

{{ url('homepage') }}

(homepage, o como lo llames en tu archivo de enrutamiento).

 74
Author: Damien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-27 20:18:53

Esto ahora está disponible de forma gratuita en plantillas twig (probado en sf2 versión 2.0.14)

{{ app.request.getBaseURL() }}

En versiones posteriores de Symfony (probadas en 2.5), prueba:

{{ app.request.getSchemeAndHttpHost() }}
 122
Author: codecowboy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-17 17:39:08

Puede utilizar el nuevo método de solicitud getSchemeAndHttpHost():

{{ app.request.getSchemeAndHttpHost() }}
 48
Author: Hugo Nogueira,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-25 20:17:11

La url base se define dentro de Symfony\Component\Routing\RequestContext.

Se puede obtener del controlador de la siguiente manera:

$this->container->get('router')->getContext()->getBaseUrl()
 32
Author: sumanchalki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-02 08:05:39

Válido desde Symfony v2.1 hasta v4.1 +

Si desea que la URL base de una aplicación Symfony, debe usar getSchemeAndHttpHost() concatenada junto con getBaseUrl(), de manera similar a como funciona getUri(), excepto sin la ruta del enrutador y la cadena de consulta.

{{ app.request.schemeAndHttpHost ~ app.request.baseUrl }}

Por ejemplo, si la URL de tu sitio web de Symfony vive en https://www.stackoverflow.com/app1/, entonces estos dos métodos devuelven estos valores:

GetSchemeAndHttpHost

https://www.stackoverflow.com

GetBaseUrl

/app1

Nota: getBaseUrl() incluye script filename (ie /app.php) si está en tu URL.

 20
Author: Matt Janssen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-25 03:01:38
 <base href="{{ app.request.getSchemeAndHttpHost() }}"/>

O del controlador

$this->container->get('router')->getContext()->getSchemeAndHttpHost()
 14
Author: user3869574,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-23 16:01:07

Para Symfony 2.3+, para obtener la url base en un controlador debe ser

$this->get('request')->getSchemeAndHttpHost();
 14
Author: Mr. 14,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-04 14:11:49

También para urls js/css/image hay una práctica función asset ()

<img src="{{ asset('image/logo.png') }}"/>
 2
Author: Sash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-29 15:10:57

En lugar de pasar la variable a la plantilla globalmente, puede definir una plantilla base y representar la 'parte global' en ella. La plantilla base se puede heredar.

Ejemplo de plantilla de renderizado de la Documentación de symfony:

<div id="sidebar">
  {% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}
</div>
 1
Author: Sethunath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-19 14:33:48
{{ dump(app.request.server.get('DOCUMENT_ROOT')) }}
 0
Author: ivan.proskuryakov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-23 19:32:58

Para la versión actual de Symfony (al escribir esta respuesta es Symfony 4.1) no acceda directamente al contenedor de servicios como se hace en algunas de las otras respuestas.

En su lugar (a menos que no utilice la configuración de servicios estándar), inyecte el objeto request por tipo-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;
    }
}

Consulte también los documentos oficiales de Symfony sobre cómo recuperar el objeto de solicitud actual.

 0
Author: Arvid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-11 12:47:24