Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Blade templates

Blade is Laravel's template engine. A template is an HTML file with simple inserts for printing data, conditions and loops. Templates live in the resources/views folder and have the .blade.php extension.

Rendering a template

The view() function finds a template by name and returns the finished page. The name welcome maps to the file resources/views/welcome.blade.php:

Route::get('/', function () {
    return view('welcome');
});

Passing data

Data is passed as the second argument — an array. Its keys become template variables:

public function show()
{
    return view('profile', ['name' => 'Anna', 'age' => 28]);
}
<h1>{{ $name }}</h1>
<p>Age: {{ $age }}</p>

Double curly braces print a value and escape HTML — this protects against XSS.

Conditions

Directives start with the @ sign:

@if ($age >= 18)
    <p>Access granted</p>
@else
    <p>Access denied</p>
@endif

Loops

<ul>
    @foreach ($posts as $post)
        <li>{{ $post->title }}</li>
    @endforeach
</ul>

For lists that may be empty, the @forelse directive is handy:

@forelse ($posts as $post)
    <li>{{ $post->title }}</li>
@empty
    <p>No posts yet.</p>
@endforelse

A shared layout

The header and footer go into a layout. The place for page content is marked with the @yield directive:

{{-- resources/views/layout.blade.php --}}
<html>
<body>
    <header>My blog</header>
    <main>@yield('content')</main>
</body>
</html>

A page extends the layout and fills the section:

@extends('layout')
 
@section('content')
    <h1>Home</h1>
@endsection

Including partials

A repeated fragment goes into its own file and is included with the @include directive. A dot in the name stands for a slash in the path:

@include('partials.menu')

Common mistake

The {!! $text !!} form prints a value without escaping. If the variable holds user input, the user can inject their own script into the page.

{{-- Dangerous for user data: --}}
{!! $comment !!}
 
{{-- Safe: --}}
{{ $comment }}

Thanks for reading!

Donate to the site — we work hard for you.