Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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::compile($string, array('name' => 'John Doe'));  ?> 

http://paste.laravel.com/ujL

like image 952
Tee Plus Avatar asked Jun 03 '13 06:06

Tee Plus


People also ask

Can I use blade template without Laravel?

Yes you can use it where ever you like.

Is Blade a template engine?

Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates.


1 Answers

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;     }  } 
like image 92
Tee Plus Avatar answered Sep 28 '22 15:09

Tee Plus