Escaping output in Laravel

Update June 2013

It looks as if Laravel 4 has gone back to the old way of doing things, during the beta phase Laravel escaped output by default: https://github.com/laravel/framework/issues/206. However, the latest documentation states that the triple curly brace now escapes output.

So here are the techniques for escaping output in both Laravel 3 and Laravel 4:


//Escaped output:
{{{ $user->username }}}

//Raw output:
{{ $user->username }}

 

Original Post - March 2013

We all know how crucial it is to escape output, but I couldn't find a way of doing this in Laravel (other than using the HTML::entities or the PHP functions). There must be a nice, clean and easy way of doing this;

As it turns out, it's very simple if you are using Laravel 3 (I've not tried earlier versions) or Laravel 4 and the blade templates:

Laravel 3


//Escaped output:
{{{ $user->username }}}

//Raw output:
{{ $user->username }}

Laravel 4


//Escaped output:
{{ $user->username }}

//Raw output:
{{{ $user->username }}}

The keen-eyed reader will notice that Laravel 4 has switched the number of braces around. I much prefer this syntax because by default output is escaped, so you have to remember to use three braces when you want raw HTML rather than vice-versa. I personally think if you are going to make a mistake it's better to escape some HTML by accident, rather than not escape values entered by a user.