Programing

웹 사이트의 기본 URL을 가져 와서 Symfony 2의 나뭇 가지에 전역으로 전달

lottogame 2020. 9. 22. 20:58
반응형

웹 사이트의 기본 URL을 가져 와서 Symfony 2의 나뭇 가지에 전역으로 전달


CodeIgniter에서 Symfony 2로 전환하고 있습니다. 누군가 다음 방법에 대한 예를 들어 주시겠습니까?

  • 기본 URL 가져 오기 (경로 특정 부분이없는 URL)
  • 이 변수를 모든 템플릿에서 사용할 수 있도록 twig 번들에 전역 적으로 전달합니다.

이 루트 URL이 필요한 이유는 무엇입니까? 직접 절대 URL을 생성 할 수 없습니까?

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

이 Twig 코드는 _demo_hello 경로에 대한 전체 http : // URL을 생성합니다.

사실, 웹 사이트의 기본 URL을 얻는 것은 홈페이지 경로의 전체 URL 만 얻는 것입니다.

{{ url('homepage') }}

( 홈페이지 또는 라우팅 파일에서 부르는 이름).


이제 twig 템플릿에서 무료로 사용할 수 있습니다 (sf2 버전 2.0.14에서 테스트 됨).

{{ app.request.getBaseURL() }}

이후 Symfony 버전 (2.5에서 테스트 됨)에서는 다음을 시도하십시오.

{{ app.request.getSchemeAndHttpHost() }}

새 요청 방법을 사용할 수 있습니다 getSchemeAndHttpHost().

{{ app.request.getSchemeAndHttpHost() }}

기본 URL은 내부에 정의되어 Symfony\Component\Routing\RequestContext있습니다.

다음과 같이 컨트롤러에서 가져올 수 있습니다.

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

Symfony v2.1부터 v4.1 +까지 유효

Symfony 애플리케이션에 대한 기본 URL을 원하는 경우 라우터 경로 및 쿼리 문자열이없는 경우를 제외하고 작동 방식 과 유사하게 getSchemeAndHttpHost()와 함께 연결 을 사용해야 합니다.getBaseUrl()getUri()

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

예를 들어 Symfony 웹 사이트 URL이에있는 https://www.stackoverflow.com/app1/경우 다음 두 메서드가 다음 값을 반환합니다.

getSchemeAndHttpHost

https://www.stackoverflow.com

getBaseUrl

/app1

참고 : URL에있는 경우 getBaseUrl()스크립트 파일 이름 (예 :)을 포함합니다 /app.php.


Symfony 2.3+의 경우 컨트롤러에서 기본 URL을 얻으려면

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

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

또는 컨트롤러에서

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

또한 js / css / image URL의 경우 편리한 함수 asset ()이 있습니다.

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

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>

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.


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

참고URL : https://stackoverflow.com/questions/6840578/getting-the-base-url-of-the-website-and-globally-passing-it-to-twig-in-symfony-2

반응형