RBlade Templates
TODO redo TOC
Introduction
RBlade is a simple, yet powerful templating engine for Ruby on Rails, inspired by Laravel Blade. Unlike some templating engines, RBlade does not restrict you from using plain Ruby code in your templates. Blade template files use the .rblade file extension and are typically stored in the app/views directory.
Displaying Data
You may display data that is passed to your RBlade views by wrapping the variable in curly braces. For example, given the following controller method:
def index
name = "Samantha"
end
You may display the contents of the name variable like so:
Hello, {{ name }}.
[!NOTE]
RBlade's{{ }}print statements are automatically sent through Rails'hfunction to prevent XSS attacks.
You are not limited to displaying the contents of the variables passed to the view. You may also print the results of any Ruby function. In fact, you can put any Ruby code you wish inside of a RBlade print directive:
The current UNIX timestamp is {{ Time.now.to_i }}.
HTML Entity Encoding
By default, RBlade {{ }} statements are automatically sent through Rails' h function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:
Hello, {!! name !!}.
[!WARNING]
Be very careful when echoing content that is supplied by users of your application. You should typically use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.
Blade and JavaScript Frameworks
Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the RBlade rendering engine an expression should remain untouched. For example:
<h1>Laravel</h1>
Hello, @{{ name }}.
In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the RBlade engine, allowing it to be rendered by your JavaScript framework.
The @ symbol may also be used to escape RBlade directives:
{{-- Blade template --}}
@@if()
<!-- HTML output -->
@if()
The @verbatim Directive
If you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the @verbatim directive so that you do not have to prefix each Blade print directive with an @ symbol:
@verbatim
<div class="container">
Hello, {{ name }}.
</div>
@endverbatim
RBlade Directives
In addition to template inheritance and displaying data, RBlade also provides convenient shortcuts for common Ruby control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with Ruby control structures while also remaining familiar to their ruby counterparts.
[!NOTE]
RBlade directives are case insensitive and ignore underscores, so depending on your preference, all of@endif,@endIfand@end_ifare identical.
If Statements
You may construct if statements using the @if, @elseif, @else, @endif, @unless, and @endunless directives. These directives function identically to their Ruby counterparts:
@unless(records.nil?)
@if (records.count === 1)
I have one record!
@elseif (records.count > 1)
I have multiple records!
@else
I don't have any records!
@endif
@endunless
In addition to the conditional directives already discussed, the @isset and @empty directives may be used as convenient shortcuts for their respective PHP functions:
TODO add nil? directive?
@isset($records)
// $records is defined and is not null...
@endisset
@empty($records)
// $records is "empty"...
@endempty
Authentication Directives
TODO add authentication directives?
The @auth and @guest directives may be used to quickly determine if the current user is authenticated or is a guest:
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest
If needed, you may specify the authentication guard that should be checked when using the @auth and @guest directives:
@auth('admin')
// The user is authenticated...
@endauth
@guest('admin')
// The user is not authenticated...
@endguest
Environment Directives
You may check if the application is running in the production environment using the @production directive:
@production
// Production specific content...
@endproduction
Or, you may determine if the application is running in a specific environment using the @env directive:
@env('staging')
// The application is running in "staging"...
@endenv
@env(['staging', 'production'])
// The application is running in "staging" or "production"...
@endenv
Session Directives
TODO add sessuib directives
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:
@session('status')
<div class="p-4 bg-green-100">
{{ $value }}
</div>
@endsession
Case Statements
Case statements can be constructed using the @case, @when, @else and @endcase directives:
@case(i)
@when(1)
First case...
@when(2)
Second case...
@else
Default case...
@endcase
Loops
In addition to conditional statements, RBlade provides simple directives for working with Ruby's loop structures:
@for (i in 0...10)
The current value is {{ i }}
@endfor
{{-- Compiles to users.each do |user| ... --}}
@each (user in users)
<p>This is user {{ user.id }}</p>
@endeach
@forelse (name in [])
<li>{{ name }}</li>
@empty
<p>No names</p>
@endforelse
@eachelse (user in users)
<li>{{ user.name }}</li>
@empty
<p>No users</p>
@endeachelse
@while (true)
<p>I'm looping forever.</p>
@endwhile
When using loops you can also skip the current iteration or end the loop using the @next and @break directives:
for (user in users)
@if (user.type == 1)
@next
@endif
<li>{{ user.name }}</li>
@if (user.number == 5)
@break
@endif
@endfor
You may also include the continuation or break condition within the directive declaration:
@foreach (user in users)
@next(user.type == 1)
<li>{{ $user->name }}</li>
@break(user.number == 5)
@endforeach
The Loop Variable
TODO can/should we add this?
While iterating through a foreach loop, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop:
@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>This is user {{ $user->id }}</p>
@endforeach
If you are in a nested loop, you may access the parent loop's $loop variable via the parent property:
@foreach ($users as $user)
@foreach ($user->posts as $post)
@if ($loop->parent->first)
This is the first iteration of the parent loop.
@endif
@endforeach
@endforeach
The $loop variable also contains a variety of other useful properties:
Conditional Classes & Styles
The @class directive conditionally adds CSS classes. The directive accepts a Hash of classes where the key contains the class or classes you wish to add, and the value is a boolean expression:
@ruby
isActive = false;
hasError = true;
@endruby
<span @class({
"p-4": true,
"font-bold": isActive,
"text-gray-500": !isActive,
"bg-red": hasError,
})></span>
<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:
@ruby
isActive = true;
@endruby
<span @style({
"background-color: red": true,
"font-weight: bold" => isActive,
})></span>
<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 print checked if the provided condition evaluates to true:
<input type="checkbox"
name="active"
value="active"
@checked(user.active)) />
Likewise, the @selected directive may be used to indicate if a given select option should be "selected":
<select name="version">
@each (version in product.versions)
<option value="{{ version }}" @selected(version == selectedVersion)>
{{ version }}
</option>
@endeach
</select>
Additionally, the @disabled directive may be used to indicate if a given element should be "disabled":
<button type="submit" @disabled(isDisabled)>Submit</button>
Moreover, the @readonly directive may be used to indicate if a given element should be "readonly":
<input type="email"
name="email"
value="[email protected]"
@readonly(!user.isAdmin) />
In addition, the @required directive may be used to indicate if a given element should be "required":
<input type="text"
name="title"
value="title"
@required(user.isAdmin) />
The @once Directive
The @once directive allows you to define a portion of the template that will only be evaluated once per rendering cycle. This may be useful for pushing a given piece of JavaScript into the page's header using stacks. For example, if you are rendering a given component within a loop, you may wish to only push the JavaScript to the header the first time the component is rendered:
@once
@push('scripts')
<script>
// Your custom JavaScript...
</script>
@endPush
@endOnce
Since the @once directive is often used in conjunction with the @push or @prepend directives, the @pushOnce and @prependOnce directives are available for your convenience:
@pushOnce('scripts')
<script>
{{-- Your javascript --}}
</script>
@endPushOnce
Additionally, you can pass an argument to the @once directive, or a second argument to the @pushonce and @prependonce directives to set the key that is used to determine if that block has already been output:
@once(:heading)
<h1>Home page</h1>
@endOnce
{{-- This block will not be output --}}
@once(:heading)
<h1>Some other title</h1>
@endOnce
[!NOTE]
The keys you use for@once,@pushOnceand@prependOnceare shared.
Raw Ruby
In some situations, it's useful to embed Ruby code into your views. You can use the RBlade @ruby directive to execute a block of plain Ruby within your template:
@ruby
counter = 1;
@endruby
TODO add require?
Or, if you only need to use PHP to import a class, you may use the @use directive:
@use('App\Models\Flight')
A second argument may be provided to the @use directive to alias the imported class:
@use('App\Models\Flight', 'FlightModel')
Comments
RBlade also allows you to define comments in your views. However, unlike HTML comments, RBlade comments are not included in the HTML returned by your application. These comments are removed from the cached views so they have no performance downsides.
{{-- This comment will not be present in the rendered HTML --}}
Components
Components are a way of including sub-views into your templates. To illustrate how to use them, we will create a simple alert component.
First, we will create a new alert.rblade file in the app/views/components/forms directory. Templates in the app/views/components directory and its subdirectories are are automatically discovered as components, so no further registration is required. Both .rblade and .html.rblade are valid extensions for RBlade components.
Once your component has been created, it may be rendered using its tag alias:
<x-forms.alert/>
Rendering Components
To display a component, you may use a Blade component tag within one of your Blade templates. Blade component tags start with the string x- followed by the kebab case name of the component class:
{{-- Render the `alert` component in app/views/components/ --}}
<x-alert/>
{{-- Render the `user-profile` component in app/views/components/ --}}
<x-user-profile/>
If the component class is in a subdirectory of app/views/components, you can use the . character to indicate directory nesting. For example, for the component app/views/components/form/inputs/text.rblade, we render it like so:
{{-- Render the `text` component in app/views/components/form/inputs/ --}}
<x-form.inputs.text/>
Namespaces
When writing components for your own application, components are automatically discovered within the app/views/components directory. Additionally, layouts in the app/views/layouts directory are automatically discovered with the layout namespace, and all views in the app/views directory are discovered with the view namespace.
Namespaced components can be rendered using the namespace as a prefix to the name separated by "::":
{{-- Render the `app` component in app/views/layouts/ --}}
<x-layout::app/>
{{-- Render the `home` component in app/views/ --}}
<x-view::home/>
Passing Data to Components
You can pass data to RBlade components using HTML attributes. Hard-coded strings can be passed to the component using simple HTML attribute strings. Ruby expressions and variables should be passed to the component via attributes that use the : character as a prefix:
<x-alert type="error" :message="message"/>
Component Properties
You can define a component's data properties using a @props directive at the top of the component. You can then reference these properties using local variables within the template:
{{-- alert.rblade --}}
@props({type: "warning", message: _required})
<div class="{{ type }}">{{ message }}</div>
The @props directive accepts a Hash where the key is the name of the attribute, and the value is the default value for the property. You can use the special _required value to represent a property with no default that must always be defined:
{{-- This will give an error because the alert component requires a message propery --}}
<x-alert/>
All properties in the @props directive are automatically removed from attributes. Properties with names that aren't valid Ruby variable names or are Ruby reserved keywords are not created as local variables. However, you can reference them via the attributes local variable:
@props({"for": _required, "data-value": nil})
<div>{{ attributes[:for] }} {{ attributes[:'data-value'] }}</div>
Short Attribute Syntax
When passing attributes to components, you may also use a "short attribute" syntax. This is often convenient since attribute names frequently match the variable names they correspond to:
{{-- Short attribute syntax... --}}
<x-profile :user_id :name />
{{-- Is equivalent to... --}}
<x-profile :user-id="user_id" :name="name" />
Escaping Attribute Rendering
Since some JavaScript frameworks such as Alpine.js also use colon-prefixed attributes, you may use a double colon (::) prefix to inform RBlade that the attribute is not a PHP expression. For example, given the following component:
<x-button ::class="{ danger: isDeleting }">
Submit
</x-button>
The following HTML will be rendered by RBlade:
<button :class="{ danger: isDeleting }">
Submit
</button>
Component Attributes
We've already examined how to pass data attributes to a component; however, sometimes you may need to specify additional HTML attributes, such as class, that are not part of the data required for a component to function. Typically, you want to pass these additional attributes down to the root element of the component template. For example, imagine we want to render an alert component like so:
<x-alert type="error" :message class="mt-4"/>
TODO remove from attributes bag using @props? Rename to attributes bag?
All of the attributes that are not part of the component's constructor will automatically be added to the component's "attribute manager". This attribute manager is automatically made available to the component via the attributes variable. All of the attributes may be rendered within the component by printing this variable:
<div {{ attributes }}>
<!-- Component content -->
</div>
Default / Merged Attributes
Sometimes you may need to specify default values for attributes or merge additional values into some of the component's attributes. To accomplish this, you may use the attribute manager's merge method. This method is particularly useful for defining a set of default CSS classes that should always be applied to a component:
<div {{ attributes.merge({"class": "alert alert-#{type}"}) }}>
{{ message }}
</div>
If we assume this component is utilized like so:
<x-alert type="error" :message class="mb-4"/>
The final, rendered HTML of the component will appear like the following:
<div class="alert alert-error mb-4">
<!-- Contents of the message variable -->
</div>
Both the class and style attributes are combined this way when using the attributes.merge method.
Non-Class Attribute Merging
When merging attributes that are not class or style, the values provided to the merge method will be considered the "default" values of the attribute. However, unlike the class and style attributes, these defaults will be overwritten if the attribute is defined in the component tag. For example:
<button {{ attributes.merge({type: "button"}) }}>
{{ slot }}
</button>
To render the button component with a custom type, it can be specified when consuming the component. If no type is specified, the button type will be used:
<x-button type="submit">
Submit
</x-button>
The rendered HTML of the button component in this example would be:
<button type="submit">
Submit
</button>
Todo add prepends
If you would like an attribute other than class or style to have its default value and injected values joined together, you can use the prepends method. In this example, the data-controller attribute will always begin with profile-controller and any additional injected data-controller values will be placed after this default value:
<div {{ attributes.merge({"data-controller": attributes.prepends("profile-controller")}) }}>
{{ slot }}
</div>
Conditionally Merge Classes
TODO this
Sometimes you may wish to merge classes if a given condition is true. You can accomplish this via the class method, which 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:
<div {{ $attributes->class(['p-4', 'bg-red' => $hasError]) }}>
{{ $message }}
</div>
If you need to merge other attributes onto your component, you can chain the merge method onto the class method:
<button {{ $attributes->class(['p-4'])->merge(['type' => 'button']) }}>
{{ $slot }}
</button>
[!NOTE]
If you need to conditionally compile classes on other HTML elements that shouldn't receive merged attributes, you can use the@classdirective.
Retrieving and Filtering Attributes
Todo this
You may filter attributes using the filter method. This method accepts a closure which should return true if you wish to retain the attribute in the attribute bag:
{{ $attributes->filter(fn (string $value, string $key) => $key == 'foo') }}
For convenience, you may use the whereStartsWith method to retrieve all attributes whose keys begin with a given string:
{{ $attributes->whereStartsWith('wire:model') }}
Conversely, the whereDoesntStartWith method may be used to exclude all attributes whose keys begin with a given string:
{{ $attributes->whereDoesntStartWith('wire:model') }}
Using the first method, you may render the first attribute in a given attribute bag:
{{ $attributes->whereStartsWith('wire:model')->first() }}
If you would like to check if an attribute is present on the component, you may use the has method. This method accepts the attribute name as its only argument and returns a boolean indicating whether or not the attribute is present:
@if ($attributes->has('class'))
<div>Class attribute is present</div>
@endif
If an array is passed to the has method, the method will determine if all of the given attributes are present on the component:
@if ($attributes->has(['name', 'class']))
<div>All of the attributes are present</div>
@endif
The hasAny method may be used to determine if any of the given attributes are present on the component:
@if ($attributes->hasAny(['href', ':href', 'v-bind:href']))
<div>One of the attributes is present</div>
@endif
You may retrieve a specific attribute's value using the get method:
{{ $attributes->get('class') }}
Slots
You will often need to pass additional content to your component via "slots". The default component slot is rendered by printing the slot variable. To explore this concept, let's imagine that an alert component has the following markup:
{{-- /app/views/components/alert.rblade --}}
<div class="alert alert-danger">
{{ slot }}
</div>
We may pass content to the slot by injecting content into the component:
<x-alert>
<strong>Whoops!</strong> Something went wrong!
</x-alert>
Sometimes a component may need to render multiple different slots in different locations within the component. Let's modify our alert component to allow for the injection of a "title" slot:
{{-- /app/views/components/alert.rblade --}}
@props({title: _required})
<span class="alert-title">{{ title }}</span>
<div class="alert alert-danger">
{{ slot }}
</div>
You may define the content of the named slot using the x-slot tag. Any content not within an explicit x-slot tag will be passed to the component in the slot variable:
<x-alert>
<x-slot:title>
Server Error
</x-slot>
<strong>Whoops!</strong> Something went wrong!
</x-alert>
TODO this
You may invoke a slot's isEmpty method to determine if the slot contains content:
<span class="alert-title">{{ title }}</span>
<div class="alert alert-danger">
@if (slot.isEmpty)
This is default content if the slot is empty.
@else
{{ slot }}
@endif
</div>
Additionally, the hasActualContent method may be used to determine if the slot contains any "actual" content that is not an HTML comment:
@if (slot.hasActualContent)
The scope has non-comment content.
@endif
Scoped Slots
TODO can we do this easily?
If you have used a JavaScript framework such as Vue, you may be familiar with "scoped slots", which allow you to access data or methods from the component within your slot. You may achieve similar behavior in Laravel by defining public methods or properties on your component and accessing the component within your slot via the $component variable. In this example, we will assume that the x-alert component has a public formatAlert method defined on its component class:
<x-alert>
<x-slot:title>
{{ $component->formatAlert('Server Error') }}
</x-slot>
<strong>Whoops!</strong> Something went wrong!
</x-alert>
Slot Attributes
Like RBlade components, you may assign additional attributes to slots such as CSS class names:
<x-card class="shadow-sm">
<x-slot:heading class="font-bold">
Heading
</x-slot>
Content
<x-slot:footer class="text-sm">
Footer
</x-slot>
</x-card>
To interact with slot attributes, you may access the attributes property of the slot's variable. For more information on how to interact with attributes, please consult the documentation on component attributes:
TODO allow class to contain a string
@props({
"heading": _required,
"footer": _required,
})
<div {{ attributes.class(['border']) }}>
<h1 {{ heading.attributes->class('text-lg': true) }}>
{{ heading }}
</h1>
{{ slot }}
<footer {{ footer.attributes.class('text-gray-700']) }}>
{{ footer }}
</footer>
</div>
Dynamic Components
TODO add this
Sometimes you may need to render a component without knowing which component should be rendered until runtime. In this situation, you may use RBlade's built-in dynamic-component component to render the component based on a runtime value or variable:
@ruby(componentName = "secondary-button")
<x-dynamic-component :component="componentName" class="mt-4" />
Registering Additional Component Directories
If you are building a package that utilizes RBlade components, or want to store your components elsewhere, you will need to manually register your component directory using the RBlade::ComponentStore.add_path method:
require "rblade/component_store"
# Auto-discover components in the app/components directory
RBlade::ComponentStore.add_path(Rails.root.join("app", "components"))
# Auto-discover components in the app/views/partials directory with the namespace "partial"
RBlade::ComponentStore.add_path(Rails.root.join("app", "views", "partials"), "partial")
If multiple directories are registered with the same namespace, RBlade will search for components in all the directories in the order they were registered.
Manually Registering Components
TODO would this be useful? It'd be useful for testing...
[!WARNING]
The following documentation on manually registering components is primarily applicable to those who are writing Laravel packages that include view components. If you are not writing a package, this portion of the component documentation may not be relevant to you.
When writing components for your own application, components are automatically discovered within the app/View/Components directory and resources/views/components directory.
However, if you are building a package that utilizes Blade components or placing components in non-conventional directories, you will need to manually register your component class and its HTML tag alias so that Laravel knows where to find the component. You should typically register your components in the boot method of your package's service provider:
use Illuminate\Support\Facades\Blade;
use VendorPackage\View\Components\AlertComponent;
/**
* Bootstrap your package's services.
*/
public function boot(): void
{
Blade::component('package-alert', AlertComponent::class);
}
Once your component has been registered, it may be rendered using its tag alias:
<x-package-alert/>
Index Components
Sometimes, when a component is made up of many RBlade templates, you may wish to group the given component's templates within a single directory. For example, imagine an "accordion" component:
<x-accordion>
<x-accordion.item>
...
</x-accordion.item>
</x-accordion>
You could make these components with files in separate directories:
/app/views/components/accordion.rblade
/app/views/components/accordion/item.rblade
However, when an index.rblade template exists in a directory, it will be rendered when referring to that directory. So instead of having to have the "index" component in a separate app/views/components/accordion.rblade, we can group the components together:
/app/views/components/accordion/index.rblade
/app/views/components/accordion/item.rblade
Accessing Parent Data
TODO this? It might be complicated
Sometimes you may want to access data from a parent component inside a child component. In these cases, you may use the @aware directive. For example, imagine we are building a complex menu component consisting of a parent <x-menu> and child <x-menu.item>:
<x-menu color="purple">
<x-menu.item>...</x-menu.item>
<x-menu.item>...</x-menu.item>
</x-menu>
The <x-menu> component may have an implementation like the following:
<!-- /resources/views/components/menu/index.rblade -->
@props(['color' => 'gray'])
<ul {{ $attributes->merge(['class' => 'bg-'.$color.'-200']) }}>
{{ $slot }}
</ul>
Because the color prop was only passed into the parent (<x-menu>), it won't be available inside <x-menu.item>. However, if we use the @aware directive, we can make it available inside <x-menu.item> as well:
<!-- /resources/views/components/menu/item.rblade -->
@aware(['color' => 'gray'])
<li {{ $attributes->merge(['class' => 'text-'.$color.'-800']) }}>
{{ $slot }}
</li>
[!WARNING]
The@awaredirective can not access parent data that is not explicitly passed to the parent component via HTML attributes. Default@propsvalues that are not explicitly passed to the parent component can not be accessed by the@awaredirective.
Forms
CSRF Field
TODO I don't think we need this?
Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the @csrf Blade directive to generate the token field:
<form method="POST" action="/profile">
@csrf
...
</form>
Method Field
TODO add this
Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The @method RBlade directive can create this field for you:
<form action="/foo/bar" method="POST">
@method('PUT')
...
</form>
Validation Errors
TODO this
The @error directive may be used to quickly check if validation error messages exist for a given attribute. Within an @error directive, you may echo the $message variable to display the error message:
<!-- /resources/views/post/create.rblade -->
<label for="title">Post Title</label>
<input id="title"
type="text"
class="@error('title') is-invalid @enderror">
@error('title')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
Since the @error directive compiles to an "if" statement, you may use the @else directive to render content when there is not an error for an attribute:
<!-- /resources/views/auth.rblade -->
<label for="email">Email address</label>
<input id="email"
type="email"
class="@error('email') is-invalid @else is-valid @enderror">
You may pass the name of a specific error bag as the second parameter to the @error directive to retrieve validation error messages on pages containing multiple forms:
<!-- /resources/views/auth.rblade -->
<label for="email">Email address</label>
<input id="email"
type="email"
class="@error('email', 'login') is-invalid @enderror">
@error('email', 'login')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
Stacks
RBlade allows you to push to named stacks which can be rendered elsewhere in another component. This can be particularly useful for specifying any JavaScript libraries required by your child views:
@push('scripts')
<script src="/example.js"></script>
@endpush
If you would like to @push content if a given boolean expression evaluates to true, you may use the @pushIf directive:
TODO add this
@pushIf(shouldPush, 'scripts')
<script src="/example.js"></script>
@endPushIf
You may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the @stack directive:
<head>
<!-- Head Contents -->
@stack('scripts')
</head>
If you would like to prepend content onto the beginning of a stack, you should use the @prepend directive:
@push('scripts')
This will be second...
@endpush
// Later...
@prepend('scripts')
This will be first...
@endprepend
Rendering Blade Fragments
TODO this?
When using frontend frameworks such as Turbo and htmx, you may occasionally need to only return a portion of a Blade template within your HTTP response. Blade "fragments" allow you to do just that. To get started, place a portion of your Blade template within @fragment and @endfragment directives:
@fragment('user-list')
<ul>
@foreach ($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ul>
@endfragment
Then, when rendering the view that utilizes this template, you may invoke the fragment method to specify that only the specified fragment should be included in the outgoing HTTP response:
return view('dashboard', ['users' => $users])->fragment('user-list');
The fragmentIf method allows you to conditionally return a fragment of a view based on a given condition. Otherwise, the entire view will be returned:
return view('dashboard', ['users' => $users])
->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
The fragments and fragmentsIf methods allow you to return multiple view fragments in the response. The fragments will be concatenated together:
view('dashboard', ['users' => $users])
->fragments(['user-list', 'comment-list']);
view('dashboard', ['users' => $users])
->fragmentsIf(
$request->hasHeader('HX-Request'),
['user-list', 'comment-list']
);
Extending Blade
TODO this?
Blade allows you to define your own 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 following example creates a @datetime($var) directive which formats a given $var, which should be an instance of DateTime:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// ...
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Blade::directive('datetime', function (string $expression) {
return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
});
}
}
As you can see, we will chain the format method onto whatever expression is passed into the directive. So, in this example, the final PHP generated by this directive will be:
<?php echo ($var)->format('m/d/Y H:i'); ?>
[!WARNING]
After updating the logic of a Blade directive, you will need to delete all of the cached Blade views. The cached Blade views may be removed using theview:clearArtisan command.
Custom Echo Handlers
TODO this? Need to do something similar for attribute manager anyway
If you attempt to "echo" an object using Blade, the object's __toString method will be invoked. The __toString method is one of PHP's built-in "magic methods". However, sometimes you may not have control over the __toString method of a given class, such as when the class that you are interacting with belongs to a third-party library.
In these cases, Blade allows you to register a custom echo handler for that particular type of object. To accomplish this, you should invoke Blade's stringable method. The stringable method accepts a closure. This closure should type-hint the type of object that it is responsible for rendering. Typically, the stringable method should be invoked within the boot method of your application's AppServiceProvider class:
use Illuminate\Support\Facades\Blade;
use Money\Money;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Blade::stringable(function (Money $money) {
return $money->formatTo('en_GB');
});
}
Once your custom echo handler has been defined, you may simply echo the object in your Blade template:
Cost: {{ $money }}
Custom If Statements
TODO this
Programming a custom directive is sometimes more complex than necessary when defining simple, custom conditional statements. For that reason, Blade provides a Blade::if method which allows you to quickly define custom conditional directives using closures. For example, let's define a custom conditional that checks the configured default "disk" for the application. We may do this in the boot method of our AppServiceProvider:
use Illuminate\Support\Facades\Blade;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Blade::if('disk', function (string $value) {
return config('filesystems.default') === $value;
});
}
Once the custom conditional has been defined, you can use it within your templates:
@disk('local')
<!-- The application is using the local disk... -->
@elsedisk('s3')
<!-- The application is using the s3 disk... -->
@else
<!-- The application is using some other disk... -->
@enddisk
@unlessdisk('local')
<!-- The application is not using the local disk... -->
@enddisk