Safely Seed Your Vue Components with Blade Double-encoding


January 29th, 2018


Editors Note: As of Laravel 5.6 this is no longer needed!

You can easily embed JSON data in your Vue components with a new Blade double-encoding method. If you use Vue components with a server-side application like Laravel, chances are that you’ve seeded Vue components with some JSON data or user-generated content (UGC) that looks something like the following:

4 <div id="app">
5 <example-component
6 :example-data="{{ json_encode([
7 'wrestler_name' => '"Mercenary" Keith Anderson'
8 ]) }}"
9 >
10 </example-component>
11 </div>

Unfortunately, if your data has HTML entities, your Vue application will get stopped dead in its tracks.

As of Laravel 5.5.29, Taylor Otwell introduced a doubleEncode() method to the Blade compiler, which solves this issue easily.

Adam Walthan Tweeted about how to use double-encoding with this example:

???? If you ever seed your Vue components with JSON data in your Blade templates, you *definitely* want to enable double-encoding.

Without it, a rogue "&quot;" in any user-submitted data might blow up your front end!

— Adam Wathan (@adamwathan) January 19, 2018

Fortunately, it’s easy to remedy by adding the new Blade::doubleEncode() method in your AppServiceProvider::boot() method:

1class AppServiceProvider extends ServiceProvider
3 /**
4 * Bootstrap any application services.
5 *
6 * @return void
7 */
8 public function boot()
9 {
10 Blade::doubleEncode();
11 }

The original <example-component> example I shared would now look like the following with double-encoding:

I’ve fought with seeding Vue components with JSON data, and it’s nice that Laravel can automatically make this stuff so much easier to deal with now!

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.