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

Linda Hamilton
發布: 2024-10-22 13:07:03
原創
948 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!