首頁  >  文章  >  後端開發  >  如何在 Laravel 中從字串編譯 Blade 模板?

如何在 Laravel 中從字串編譯 Blade 模板?

Linda Hamilton
Linda Hamilton原創
2024-10-22 13:07:03949瀏覽

How to Compile Blade Templates from Strings in Laravel?

從字串編譯刀片模板

可以從字串編譯刀片模板,而不是依賴視圖檔。為此,您可以擴展現有的 BladeCompiler 類別並實作自訂方法。

擴充BladeCompiler 類別

<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('?>'.$generated);
        }

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

        $content = ob_get_clean();

        return $content;
    }

}</code>

用法

您可以使用擴充的compileWithsithsithpiths :

<code class="php">$string = '<h2>{{ $name }}</h2>';
$compiled = BladeCompiler::compileWiths($string, array('name' => 'John Doe'));
echo $compiled;</code>

以上是如何在 Laravel 中從字串編譯 Blade 模板?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn