Laravel의 문자열에서 블레이드 템플릿을 어떻게 컴파일할 수 있습니까?

Patricia Arquette
풀어 주다: 2024-10-22 12:03:02
원래의
124명이 탐색했습니다.

How Can Blade Templates Be Compiled from Strings in Laravel?

문자열에서 블레이드 템플릿 컴파일

인기 있는 웹 애플리케이션 프레임워크인 Laravel에서는 Blade가 기본 템플릿 엔진입니다. 일반적으로 블레이드 보기는 보기 파일에 저장됩니다. 그러나 파일을 보는 대신 문자열에서 블레이드 템플릿을 컴파일할 가능성에 대한 의문이 제기되었습니다.

제공된 코드는 문자열에서 블레이드 템플릿을 컴파일하려는 시도를 보여줍니다.

<code class="php">$string = '<h2>{{ $name }}</h2>';
echo Blade::compile($string, array('name' => 'John Doe'));</code>
로그인 후 복사

To BladeCompiler의 기능을 확장하기 위해 사용자 정의 BladeCompiler 클래스가 생성되었습니다. 새로운 compileWiths() 메서드는 문자열과 인수 배열을 입력으로 사용합니다. 문자열을 컴파일하고, 전달된 인수를 추출하고, 예외 처리기 내에서 컴파일된 코드를 평가합니다.

아래 업데이트된 코드는 구현을 보여줍니다.

<code class="php">namespace Laravel\Enhanced;

use Illuminate\View\Compilers\BladeCompiler as LaravelBladeCompiler;

class BladeCompiler extends LaravelBladeCompiler {

    /**
     * Compile blade template with passing arguments.
     *
     * @param string $value HTML-code including blade
     * @param array $args Array of values used in blade
     * @return string
     */
    public function compileWiths($value, array $args = array())
    {
        $generated = parent::compileString($value);

        ob_start() and extract($args, EXTR_SKIP);

        // We'll include the view contents for parsing within a catcher
        // so we can avoid any WSOD errors. If an exception occurs we
        // will throw it out to the exception handler.
        try
        {
            eval('?>'.$generated);
        }

        // If we caught an exception, we'll silently flush the output
        // buffer so that no partially rendered views get thrown out
        // to the client and confuse the user with junk.
        catch (\Exception $e)
        {
            ob_get_clean(); throw $e;
        }

        $content = ob_get_clean();

        return $content;
    }

}</code>
로그인 후 복사

위 내용은 Laravel의 문자열에서 블레이드 템플릿을 어떻게 컴파일할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!