Skip to content

Leaf + Blade

Blade is Laravel's own templating engine that makes creating dynamic views easy. It lets you mix regular PHP code with its own features for more flexibility, has a clean syntax and caches your views for faster performance.

Leaf Blade is an adaptation of the original Blade package that allows you to use Blade templates in your Leaf PHP projects powered by jenssegers/blade.

New to Blade?

This video by The Net Ninja will help you get started with blade.

Setting Up

Blade comes with Leaf MVC out of the box, fully configured and ready to use, however, if you're using Leaf on its own, you can install Blade using the Leaf CLI or Composer.

bash
leaf install blade
bash
composer require leafs/blade
Configuring your paths

After installing Blade in your Leaf app, you just need to inform Leaf of Blade's existence:

php
app()->attachView(Leaf\Blade::class);

This will magically set up Blade for you and pop up a blade() function you can use to render your Blade views.

php
app()->blade()->configure([
  'views' => 'views',
  'cache' => 'storage/cache'
]);

Once again, this is only necessary if you're using Leaf on its own. If you're using Leaf MVC, Blade is already set up for you.

Magic! You can now use Blade to create and render your views.

Creating Blade Views

Blade views are a pretty sweet mixture of HTML, PHP, and clean syntax. You can create a new Blade view by creating a new file with the .blade.php extension in your "views" folder. Here's an example of a simple Blade view:

blade
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <h1>Hello, {{ $name }}</h1>
</body>
</html>

This should look pretty familiar if you know HTML (of course you do). The only difference is the {{ $name }} part. This is Blade's way of creating a variable in your view. When you render this view, Blade will allow you pass in a variable called $name and it will be displayed in place of {{ $name }}. Let's see how you can render this view.

Rendering Blade Views

Remember we set up Blade earlier? Now we can use it to render our Blade views. Here's how you can render the hello.blade.php view we created earlier:

php
echo app()->blade()->render('hello', ['name' => 'Michael']);

This will render the hello.blade.php view and pass in a variable called name with the value Michael. When you open the view in your browser, you should see a big "Hello, Michael" on your screen.

Directives included in Leaf Blade

Although Leaf Blade is just an adaptation of the original Blade package, it comes pre-packaged with some original Blade directives remodelled to work with Leaf and a few custom directives to make your life easier. You can find all common Blade directives in the Blade documentation.

Here are some of the directives you can use in your Blade views:

CSRF protection

The @csrf directive generates a hidden CSRF token field for forms. This is useful when you want to include a CSRF token in your form.

blade
<form method="POST">
  @csrf
  ...
</form>

Working with JSON

You can use the @json directive to convert a PHP array to a JSON string. This is useful when you want to pass a JSON string to a JavaScript variable.

blade
<script>
  var app = @json($array);
</script>

Loading assets with vite

You can use the @vite directive to load assets like CSS and JS files in your Blade views using Vite.

blade
@vite('app.js')
@vite(['app.js', 'app.css'])

Adding Alpine.js

Alpine.js is a minimal framework for composing JavaScript behavior in your views. You can use the @alpine directive to add Alpine.js to your Blade views.

blade
<head>
  ...

  @alpine
</head>

Checking for null

You can use the @isNull directive to check if a variable is null.

blade
@isNull($variable)
  <p>This will only show if $variable is null</p>
@else
  <p>This will show if $variable is not null</p>
@endisNull

Conditional rendering with env

You can use the @env directive to conditionally render content based on the environment.

blade
@env('local')
  <p>This will only show in the local environment</p>
@else
  <p>This will show in all other environments</p>
@endenv

Working with sessions

The @session directive may be used to determine if a session value exists. If the session value exists, the template contents within the @session and @endsession directives will be evaluated. Within the @session directive's contents, you may echo the $value variable to display the session value:

blade
@session('status')
  <div class="p-4 bg-green-100">
    {{ $value }}
  </div>
@endsession

Working with flash messages

The @flash directive may be used to determine if a flash message exists. If the flash message exists, the template contents within the @flash and @endflash directives will be evaluated. Within the @flash directive's contents, you may echo the $message variable to display the flash message:

blade
@flash('status')
  <div class="p-4 bg-green-100">
    {{ $message }}
  </div>
@endflash

Conditional Classes & Styles

The @class directive conditionally compiles a CSS class string. The directive accepts an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression. If the array element has a numeric key, it will always be included in the rendered class list:

blade
@php
  $isActive = false;
  $hasError = true;
@endphp

<span @class([
  'p-4',
  'font-bold' => $isActive,
  'text-gray-500' => ! $isActive,
  'bg-red' => $hasError,
])></span>

OUTPUT: <span class="p-4 text-gray-500 bg-red"></span>

Likewise, the @style directive may be used to conditionally add inline CSS styles to an HTML element:

blade
@php
  $isActive = true;
@endphp

<span @style([
  'background-color: red',
  'font-weight: bold' => $isActive,
])></span>

OUTPUT: <span style="background-color: red; font-weight: bold;"></span>

Additional Attributes

For convenience, you may use the @checked directive to easily indicate if a given HTML checkbox input is "checked". This directive will echo checked if the provided condition evaluates to true:

blade
<input
  type="checkbox"
  name="active"
  value="active"
  @checked($isActive)
/>

Likewise, the @selected directive may be used to indicate if a given select option should be "selected":

blade
<select name="version">
  @foreach ($product->versions as $version)
    <option ... @selected($shouldBeSelected)>
      ...
    </option>
  @endforeach
</select>

Additionally, the @disabled directive may be used to indicate if a given element should be "disabled":

blade
<button type="submit" @disabled($shouldBeDisabled)>Submit</button>

Moreover, the @readonly directive may be used to indicate if a given element should be "readonly":

blade
<input
  type="email"
  name="email"
  value="email@laravel.com"
  @readonly($shouldBeReadonly)
/>

In addition, the @required directive may be used to indicate if a given element should be "required":

blade
<input
  type="text"
  name="title"
  value="title"
  @required($shouldBeRequired)
/>

Leaf Auth

The @auth and @guest directives may be used to quickly determine if the current user is authenticated or is a guest:

blade
@auth
  // The user is authenticated...
@endauth

@guest
  // The user is not authenticated...
@endguest

Roles & Permissions

You can use the @is directive to check if the current user has a specific role:

blade
@is('admin')
  // The user has the admin role...
@else
  // The user does not have the admin role...
@endis

You can also use the @can directive to check if the current user has a specific permission:

blade
@can('edit articles')
  // The user can edit articles...
@else
  // The user cannot edit articles...
@endcan

Extending Blade Views

Blade allows you to define custom directives using the directive() method. When the Blade compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains. The callback is free to return the value of its contents however you like:

php
app()->blade()->directive('datetime', function ($expression) {
    return "<?php echo tick({$expression})->format('F d, Y g:i a'); ?>";
});

Which allows you to use the following in your blade template:

blade
Current date: @datetime($date)

This will output the current date in the format F d, Y g:i a. You can define as many custom directives as you want to make your Blade views more powerful.

Conclusion

This is just the beginning of what you can do with Blade. Blade is a powerful templating engine that allows you to create dynamic views with ease. You can use Blade to create complex views with loops, conditions, and even include other views. As this is just an adapter for the original Blade package, you can check out the Blade documentation for more information on what you can do with Blade.

Released under the MIT License.