Laravel で文字列から Blade テンプレートをコンパイルするにはどうすればよいですか?

Patricia Arquette
リリース: 2024-10-22 12:03:02
オリジナル
124 人が閲覧しました

How Can Blade Templates Be Compiled from Strings in Laravel?

Compiling Blade Templates from Strings

In Laravel, a popular web application framework, Blade is the default template engine. Typically, Blade views are stored in view files. However, a question arose regarding the possibility of compiling Blade templates from strings rather than view files.

The provided code demonstrates an attempt to compile a Blade template from a string:

<code class="php">$string = '<h2>{{ $name }}</h2>';
echo Blade::compile($string, array('name' => 'John Doe'));</code>
ログイン後にコピー

To extend the functionality of BladeCompiler, a custom BladeCompiler class was created. The new compileWiths() method takes a string and an array of arguments as inputs. It compiles the string, extracts the passed arguments, and evaluates the compiled code within an exception handler.

The updated code below shows the implementation:

<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('?&gt;'.$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 で文字列から Blade テンプレートをコンパイルするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!