Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Blade from string instead of File

How can I render an string which contains blade syntax?

View::make('directory.file-name')->with('var', $var);  // Usual usage

View::render('{{$var}}')->with('var', $var); // Like this for Example

I use wrote an script that produces blade syntax and I want to give it's output directly to blade engine if possible.

Thanks

like image 735
Positivity Avatar asked Feb 04 '14 15:02

Positivity


2 Answers

I don't recommend to use 'Blade::compileString' as it won't fully render PHP as View does.

This is a working version of my actual Blade string renderer. You may use it for database content or any string you want to render as you would with a .blade.php file. Tested with Laravel 4. Fully commented and explained.

Do not forget to create the 'cache' folder inside views

This function generates the fileview

public function generateViewFile($html, $url, $updated_at)
{
    // Get the Laravel Views path
    $path = \Config::get('view.paths.0');

    // Here we use the date for unique filename - This is the filename for the View
    $viewfilename = $url."-".hash('sha1', $updated_at);

    // Full path with filename
    $fullfilename = $path."/cache/".$viewfilename.".blade.php";

    // Write the string into a file
    if (!file_exists($fullfilename))
    {
        file_put_contents($fullfilename, $html);
    }

    // Return the view filename - This could be directly used in View::make
    return $viewfilename;
}

This is the ContentController route renderer

public function getIndex($uri = false)
{
    // In my real ContentController I get the page from the DB here
    //
    // $page = Page::findByUrl($uri);
    // $content = $page->content;
    // $updated_at = $page->updated_at;
    // $url = $page->url;

    $content = '<h1>This is the page to render</h1>';
    $updated_at = '2015-07-15 02:40:55';
    $url = '/blog/new-article';

    // Will write the file when needed and return the view filename
    $filename = $this->generateViewFile($content, $url, $updated_at);

    // Fully render and output the content
    return View::make('cache/'.$filename);
}

Handler at the end of the routes.php. Even if this is not required, this is to present a fully testeable solution.

Route::get('{all}', 'ContentController@getIndex')->where('all', '.*');
like image 126
Heroselohim Avatar answered Jan 03 '23 12:01

Heroselohim


Hope this helps,

https://github.com/TerrePorter/StringBladeCompiler

This is a fork of the next link that removes the db model requirement and replaces it with a array that requires three required keys ('template', 'cache_key', 'updated_at') instead of the full Eloquent model.

https://github.com/Flynsarmy/laravel-db-blade-compiler

This uses a Eloquent model to get the template.

like image 26
Terre Porter Avatar answered Jan 03 '23 11:01

Terre Porter