Safely Seed Your Vue Components with Blade Double-encoding

Safely Seed Your Vue Components with Blade Double-encoding

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:

@extends('layout')
@section('content')

    <div id="app">
        <example-component
            :example-data="{{ json_encode([
                'wrestler_name' => '"Mercenary" Keith Anderson'
            ]) }}"
        >
        </example-component>
    </div>

@endsection

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:

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

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::doubleEncode();
    }
}

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: Laravel Tutorials / Blade


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Full-Stack Developer
Tampa
Nu Image Medical
Senior Software Developer
Remote (US ONLY)/Kenilworth, NJ
Diversified
Senior Back-end Laravel API Developer - Immediate Contract (Full Time)
Remote
ApproveMe // Document Signing
Web Development Project Manager
Houston, TX
Swyft Filings
Experienced Laravel/VueJS Developer (Freelance)
Remote (preferably in the US)
Prosperly LLC
Senior React / Laravel Developer
Remote
The C.A.S.E. Engineering Group
Software Engineer
Boston
ButcherBox