Is there any way to compile a blade template from a string?

blade string interpolation
laravel render view
blade directive
blade::if
laravel blade comments
laravel blade json
laravel blade variable
laravel blade slots

How can I compile a blade template from a string rather than a view file, like the code below:

<?php
$string = '<h2>{{ $name }}</h2>';
echo Blade::compile($string, array('name' => 'John Doe')); 
?>

http://paste.laravel.com/ujL

I found the solution by extending BladeCompiler.

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

}

Compile a string like Blade Template in Laravel · GitHub, so we can avoid any WSOD errors. If an exception occurs we. // will throw it out to the exception handler. try. {. eval('?>'.$generated);. php - not - Is there any way to compile a blade template from a string? render blade template to string (3)

Small modification to the above script. You can use this function inside any class without extending the BladeCompiler class.

public function bladeCompile($value, array $args = array())
{
    $generated = \Blade::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('?>'.$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;
}

Render template from blade template in database, My problem is, how to pass the Blade template and compile it with data. called compileString, but it only able to render the given template How can you evaluate that piece of PHP code against a custom array of variables? How to compile a blade template from any folder other than resources/views? Posted 4 years ago by iamfaiz In Laravel we have this handy view() helper function that returns the compiled template.

I'm not using blade this way but I thought that the compile method accepts only a view as argument.

Maybe you're looking for:

Blade::compileString()

Compile inline blade template, Is there any build-in clean way to use inline blade template as: $engine->​render(" also see: https://github.com/nicmart/StringTemplate. Blade is a HTML Template Compiler for Node.js, inspired by Jade/Pug and Haml. It works like this Write up your template in Blade (which is a Pug-like language)

I just stumbled upon the same requirement! For me, i had to fetch a blade template stored in DB & render it to send email notifications.

I did this in laravel 5.8 by kind-of Extending \Illuminate\View\View. So, basically i created the below class & named him StringBlade (I couldn't find a better name atm :/)

<?php

namespace App\Central\Libraries\Blade;

use Illuminate\Filesystem\Filesystem;

class StringBlade implements StringBladeContract
{
    /**
     * @var Filesystem
    */
    protected $file;

    /**
     * @var \Illuminate\View\View|\Illuminate\Contracts\View\Factory
    */
    protected $viewer;

    /**
     * StringBlade constructor.
     *
     * @param Filesystem $file
     */
    public function __construct(Filesystem $file)
    {
        $this->file = $file;
        $this->viewer = view();
    }

    /**
     * Get Blade File path.
     *
     * @param $bladeString
     * @return bool|string
     */
    protected function getBlade($bladeString)
    {
        $bladePath = $this->generateBladePath();

        $content = \Blade::compileString($bladeString);

        return $this->file->put($bladePath, $content)
            ? $bladePath
            : false;
    }

    /**
     * Get the rendered HTML.
     *
     * @param $bladeString
     * @param array $data
     * @return bool|string
     */
    public function render($bladeString, $data = [])
    {
        // Put the php version of blade String to *.php temp file & returns the temp file path
        $bladePath = $this->getBlade($bladeString);

        if (!$bladePath) {
            return false;
        }

        // Render the php temp file & return the HTML content
        $content = $this->viewer->file($bladePath, $data)->render();

        // Delete the php temp file.
        $this->file->delete($bladePath);

        return $content;
    }

    /**
     * Generate a blade file path.
     *
     * @return string
     */
    protected function generateBladePath()
    {
        $cachePath = rtrim(config('cache.stores.file.path'), '/');
        $tempFileName = sha1('string-blade' . microtime());
        $directory = "{$cachePath}/string-blades";

        if (!is_dir($directory)) {
            mkdir($directory, 0777);
        }

        return "{$directory}/{$tempFileName}.php";
    }
}

Is there any way to compile a blade template from a string?, How can I compile a blade template from a string rather than a view file, like If an exception occurs we // will throw it out to the exception handler. try { eval('?>'. Render Blade templates from string value. Reworked version to allow for array to be passed to the view function instead of template file name. This is a direct extension of \Illuminate\View\View and is build to replace its usage.

It's a old question. But I found a package which makes the job easier.

Laravel Blade String Compiler renders the blade templates from the string value. Check the documentation on how to install the package.

Here is an example:

$template = '<h1>{{ $name }}</h1>';  // string blade template

return view (['template' => $template], ['name' => 'John Doe']);

Note: This package is not compatible with the Laravel 5.7

Is there any way to compile a blade template from a string?, How can I compile a blade template from a string rather than a view file, like the code below: <?php $string = '<h2>{{ $name }}</h2>'; echo  Blade Templating. Blade templating is a direct adaptation of Laravel's Blade templating. Blade is a simple and powerful templating engine driven by view template inheritance and sections. All Blade templates use the .blade.php extension. Modern IDEs, such as phpStorm, will recognise them and provide syntax highlighting support.

wpb/string-blade-compiler, Laravel Blade String Compiler, render string as blade templates. There is no need to add them to the /config/app.php file. existing file template load (the original View() method return view ('bladetemplatefile',['token' => 'I  Blade view files use the .blade.php file extension and are typically stored in the resources/views directory. Template Inheritance. Defining A Layout. Two of the primary benefits of using Blade are template inheritance and sections. To get started, let's take a look at a simple example. First, we will examine a "master" page layout.

Blade Templates - Laravel, In fact, all Blade views are compiled into plain PHP code and cached until they Two of the primary benefits of using Blade are template inheritance and sections. In fact, you can put any PHP code you wish inside of a Blade echo statement: These shortcuts provide a very clean, terse way of working with PHP control  Blade is the default template engine for Laravel (since Laravel 2 in 2011). The syntax is originally inspired by the ASP.net Razor syntax and provides a cleaner way to write your templates.

Blade Templating - Templates - Laravel, WARNING You're browsing the documentation for an old version of Laravel. One method of using templates in Laravel is via controller layouts. If you need to display a string that is wrapped in curly braces, you may escape the Blade When a Blade file is compiled, each custom extension is called with the view  Focus on the parser first. Right now, parsing a string of Blade accounts for about 80% of the work that needs to be done to compile a Blade template. Since, Blade's parser is automatically generated by PEG.js, there is not much we can do here except tweak the grammar, build a new parser from scratch, or improve the PEG.js library.

Comments
  • The question should be, why would you even need to do this?
  • You've written some code that looks good - what's wrong with it?
  • I have tried $string = '<h2>{{ $name }}</h2>'; echo Blade::compileString($string, array('name' => 'John Doe')); nothing returned.
  • This is almost a duplicate of stackoverflow.com/questions/21556981/… Just pointing the link where you would find more solutions
  • David Barker, it should be a StackExchange policy that people who respond just to lecture the asker about what question they should be asking instead, should have all their SE accounts terminated, all their known email addresses blacklisted for life, and all their contributions scrubbed. It's precisely that annoying.
  • Thanks it helped a lot. Just to help someone like me I can add to your post that a way to instancing a custom compiler extension is to pass filesystem instance ad path to compiled views to the constructor: $myBlade = new MyBlade(App::make('files'), App::make('path').'/storage/views');
  • How did you get laravel to use this blade compiler?
  • This solution works quite good. However, I have noticed an issue with foreach loops. <ul> @foreach($items as $item) <li>{{ $item }}</li> @endforeach </ul> This code does not render and I get this error: Undefined variable: __env Is there a solution?
  • $mail_template = MailTemplate::where('name',$name)->first(); $this->bladeCompile($mail_template->body,array('price' => 300));
  • $string = '<h2>{{ $name }}</h2>'; echo Blade::compileString($string, array('name' => 'John Doe')); "name" is not assign to the template.
  • Dope dude thanks! StringBlade is sick! its like String Cheese...... kinda.. haha edit: orrrrrr Sling Blade!?
  • The answers from above will solve the issue without any package.
  • Unfortunately, this package is not compatible with Laravel 5.7.*