arrow_back
Back

Laravel Blade: templates, directives, and components

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

open_in_new Documentation .

Display a variable:

<!-- With escaping -->
{{ $name }}
{{ someFuncThatReturnsValue() }}

<!-- Without escaping -->
{!! $name !!}
{!! someFuncThatReturnsValue() !!}

Skip for Blade (we will get the string as it is):

@{{ title }}

We can comment the content:

{{-- $name --}}

Get URL by a route name:

{{ route('home') }}
{{ route('page.about') }}

If statements

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif
@unless (Auth::check())
    You are not signed in.
@endunless
@isset($records)
    // $records is defined and is not null...
@endisset
 
@empty($records)
    // $records is "empty"...
@endempty

Main layout

We can create a main layout: /resources/views/layouts/main.blade.php:

<html>
<body>
    @yield('content')
</body>
</html>

View:

@extends('layouts.main')

@section('content')
...
@endsection

Override a section

Main template:

<html>
<head>
@section('head')
... // Default tags
@show
</head>
<body>
    @yield('content')
</body>
</html>

View:

@extends('layouts.main')

@section('content')
...
@endsection

@section('head')
// Custom tags
@endsection

We can add content instead of overwriting:

@extends('layouts.main')

@section('content')
...
@endsection

@section('head')
    @parent
    // Custom tags
@endsection

Layout parts

We can place them in /resources/views/layouts/.

In view:

@include('layouts.footer')

Helpers

Path to the web directory:

<script src="{{ asset('js/scripts.js' }}"></script>

We should change this path with ASSET_URL env var.

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Laravel Mix: compiling assets, webpack, and frontend build

arrow_forward