Heim  >  Artikel  >  Backend-Entwicklung  >  Wie kompiliere ich Blade-Vorlagen aus Strings in Laravel?

Wie kompiliere ich Blade-Vorlagen aus Strings in Laravel?

Linda Hamilton
Linda HamiltonOriginal
2024-10-22 13:07:03949Durchsuche

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>

Das obige ist der detaillierte Inhalt vonWie kompiliere ich Blade-Vorlagen aus Strings in Laravel?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn