Laravel 4: Rendering a View to a String

2 min read

Laravel 4 offers Views, a way to separate your applications controllers and business logic from your presentation layer. Sometimes, it can be useful to render the view into a local variable instead of outputting it to the client. You are probably used to returning views to the web client by using something like this:

<?php

Route::get('/', function() {

    return View::make('hello');

});

This will simply return a view named hello.php or hello.blade.php (if you are using blade) from the views folder to the web client. If you need to 'render' the view and store it in a variable you can use this code:

<?php

Route::get('/', function() {

    $myViewData = View::make('hello')->render();

});

This is incredibly useful when you need to get the view as a string to do further processing on it. I use this in one project where I take the view data to generate a PDF of the web page using wkhtmltopdf. I may create a tutorial on how to do this using Laravel 4 at a later date.

Comments

There are no comments. Be the first to comment!

Up next