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

Linda Hamilton
リリース: 2024-10-22 13:07:03
オリジナル
948 人が閲覧しました

How to Compile Blade Templates from Strings in Laravel?

Compiling Blade Templates from Strings

It is possible to compile blade templates from strings rather than relying on view files. To do this, you can extend the existing BladeCompiler class and implement a custom method.

Extended BladeCompiler Class

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

        // Include view contents for parsing within a catcher
        try
        {
            eval('?&gt;'.$generated);
        }

        // Silent flush output buffer in case of exception
        catch (\Exception $e)
        {
            ob_get_clean(); throw $e;
        }

        $content = ob_get_clean();

        return $content;
    }

}</code>
ログイン後にコピー

Usage

You can use the extended compileWiths method to compile blade templates from strings:

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

以上がLaravelで文字列からブレードテンプレートをコンパイルするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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