rblade 0.2.5 → 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
data/README.md ADDED
@@ -0,0 +1,1803 @@
1
+ # RBlade Templates
2
+
3
+ - [Introduction](#introduction)
4
+ - [Supercharging Blade With Livewire](#supercharging-blade-with-livewire)
5
+ - [Displaying Data](#displaying-data)
6
+ - [HTML Entity Encoding](#html-entity-encoding)
7
+ - [Blade and JavaScript Frameworks](#blade-and-javascript-frameworks)
8
+ - [Blade Directives](#blade-directives)
9
+ - [If Statements](#if-statements)
10
+ - [Switch Statements](#switch-statements)
11
+ - [Loops](#loops)
12
+ - [The Loop Variable](#the-loop-variable)
13
+ - [Conditional Classes](#conditional-classes)
14
+ - [Additional Attributes](#additional-attributes)
15
+ - [Including Subviews](#including-subviews)
16
+ - [The `@once` Directive](#the-once-directive)
17
+ - [Raw PHP](#raw-php)
18
+ - [Comments](#comments)
19
+ - [Components](#components)
20
+ - [Rendering Components](#rendering-components)
21
+ - [Passing Data to Components](#passing-data-to-components)
22
+ - [Component Attributes](#component-attributes)
23
+ - [Reserved Keywords](#reserved-keywords)
24
+ - [Slots](#slots)
25
+ - [Inline Component Views](#inline-component-views)
26
+ - [Dynamic Components](#dynamic-components)
27
+ - [Manually Registering Components](#manually-registering-components)
28
+ - [Anonymous Components](#anonymous-components)
29
+ - [Anonymous Index Components](#anonymous-index-components)
30
+ - [Data Properties / Attributes](#data-properties-attributes)
31
+ - [Accessing Parent Data](#accessing-parent-data)
32
+ - [Anonymous Components Paths](#anonymous-component-paths)
33
+ - [Building Layouts](#building-layouts)
34
+ - [Layouts Using Components](#layouts-using-components)
35
+ - [Layouts Using Template Inheritance](#layouts-using-template-inheritance)
36
+ - [Forms](#forms)
37
+ - [CSRF Field](#csrf-field)
38
+ - [Method Field](#method-field)
39
+ - [Validation Errors](#validation-errors)
40
+ - [Stacks](#stacks)
41
+ - [Service Injection](#service-injection)
42
+ - [Rendering Inline Blade Templates](#rendering-inline-blade-templates)
43
+ - [Rendering Blade Fragments](#rendering-blade-fragments)
44
+ - [Extending Blade](#extending-blade)
45
+ - [Custom Echo Handlers](#custom-echo-handlers)
46
+ - [Custom If Statements](#custom-if-statements)
47
+
48
+ <a name="introduction"></a>
49
+ ## Introduction
50
+
51
+ RBlade is a simple, yet powerful templating engine for Ruby on Rails, inspired by [Laravel Blade](https://laravel.com/docs/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.
52
+
53
+ <a name="displaying-data"></a>
54
+ ## Displaying Data
55
+
56
+ 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:
57
+
58
+ ```ruby
59
+ def index
60
+ name = "Samantha"
61
+ end
62
+ ```
63
+
64
+ You may display the contents of the `name` variable like so:
65
+
66
+ ```rblade
67
+ Hello, {{ name }}.
68
+ ```
69
+
70
+ > [!NOTE]
71
+ > RBlade's `{{ }}` echo statements are automatically sent through Rails' `h` function to prevent XSS attacks.
72
+
73
+ 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 Blade echo statement:
74
+
75
+ ```rblade
76
+ The current UNIX timestamp is {{ Time.now.to_i }}.
77
+ ```
78
+
79
+ <a name="html-entity-encoding"></a>
80
+ ### HTML Entity Encoding
81
+
82
+ 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:
83
+
84
+ ```rblade
85
+ Hello, {!! name !!}.
86
+ ```
87
+
88
+ > [!WARNING]
89
+ > 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.
90
+
91
+ <a name="blade-and-javascript-frameworks"></a>
92
+ ### Blade and JavaScript Frameworks
93
+
94
+ 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:
95
+
96
+ ```rblade
97
+ <h1>Laravel</h1>
98
+
99
+ Hello, @{{ name }}.
100
+ ```
101
+
102
+ 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.
103
+
104
+ The `@` symbol may also be used to escape RBlade directives:
105
+
106
+ ```rblade
107
+ {{-- Blade template --}}
108
+ @@if()
109
+
110
+ <!-- HTML output -->
111
+ @if()
112
+ ```
113
+
114
+ <a name="the-at-verbatim-directive"></a>
115
+ #### The `@verbatim` Directive
116
+
117
+ **TODO: Add verbatim directive**
118
+
119
+ 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 echo statement with an `@` symbol:
120
+
121
+ ```rblade
122
+ @verbatim
123
+ <div class="container">
124
+ Hello, {{ name }}.
125
+ </div>
126
+ @endverbatim
127
+ ```
128
+
129
+ <a name="blade-directives"></a>
130
+ ## Blade Directives
131
+
132
+ In addition to template inheritance and displaying data, Blade 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 PHP control structures while also remaining familiar to their ruby counterparts.
133
+
134
+ <a name="if-statements"></a>
135
+ ### If Statements
136
+
137
+ You may construct `if` statements using the `@if`, `@elseif`, `@else`, `@endif`, `@unless`, and `@endunless` directives. These directives function identically to their Ruby counterparts:
138
+
139
+ ```blade
140
+ @unless(records.nil?)
141
+ @if (records.count === 1)
142
+ I have one record!
143
+ @elseif (records.count > 1)
144
+ I have multiple records!
145
+ @else
146
+ I don't have any records!
147
+ @endif
148
+ @endunless
149
+ ```
150
+
151
+ In addition to the conditional directives already discussed, the `@isset` and `@empty` directives may be used as convenient shortcuts for their respective PHP functions:
152
+ **TODO add nil? directive?**
153
+ ```blade
154
+ @isset($records)
155
+ // $records is defined and is not null...
156
+ @endisset
157
+
158
+ @empty($records)
159
+ // $records is "empty"...
160
+ @endempty
161
+ ```
162
+
163
+ <a name="authentication-directives"></a>
164
+ #### Authentication Directives
165
+ **TODO add authentication directives?**
166
+ The `@auth` and `@guest` directives may be used to quickly determine if the current user is [authenticated](/docs/{{version}}/authentication) or is a guest:
167
+
168
+ ```blade
169
+ @auth
170
+ // The user is authenticated...
171
+ @endauth
172
+
173
+ @guest
174
+ // The user is not authenticated...
175
+ @endguest
176
+ ```
177
+
178
+ If needed, you may specify the authentication guard that should be checked when using the `@auth` and `@guest` directives:
179
+
180
+ ```blade
181
+ @auth('admin')
182
+ // The user is authenticated...
183
+ @endauth
184
+
185
+ @guest('admin')
186
+ // The user is not authenticated...
187
+ @endguest
188
+ ```
189
+
190
+ <a name="environment-directives"></a>
191
+ #### Environment Directives
192
+ **TODO add environment directives?**
193
+ You may check if the application is running in the production environment using the `@production` directive:
194
+
195
+ ```blade
196
+ @production
197
+ // Production specific content...
198
+ @endproduction
199
+ ```
200
+
201
+ Or, you may determine if the application is running in a specific environment using the `@env` directive:
202
+
203
+ ```blade
204
+ @env('staging')
205
+ // The application is running in "staging"...
206
+ @endenv
207
+
208
+ @env(['staging', 'production'])
209
+ // The application is running in "staging" or "production"...
210
+ @endenv
211
+ ```
212
+
213
+ <a name="session-directives"></a>
214
+ #### Session Directives
215
+ **TODO add sessuib directives**
216
+ The `@session` directive may be used to determine if a [session](/docs/{{version}}/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:
217
+
218
+ ```blade
219
+ @session('status')
220
+ <div class="p-4 bg-green-100">
221
+ {{ $value }}
222
+ </div>
223
+ @endsession
224
+ ```
225
+
226
+ <a name="switch-statements"></a>
227
+ ### Case Statements
228
+
229
+ Case statements can be constructed using the `@case`, `@when`, `@else` and `@endcase` directives:
230
+
231
+ ```blade
232
+ @case(i)
233
+ @when(1)
234
+ First case...
235
+ @when(2)
236
+ Second case...
237
+ @else
238
+ Default case...
239
+ @endcase
240
+ ```
241
+
242
+ <a name="loops"></a>
243
+ ### Loops
244
+
245
+ In addition to conditional statements, RBlade provides simple directives for working with Ruby's loop structures. Again, each of these directives functions identically to their Ruby counterparts:
246
+
247
+ ```blade
248
+ @for (i in 0...10)
249
+ The current value is {{ i }}
250
+ @endfor
251
+
252
+ @each (user in users)
253
+ <p>This is user {{ user.id }}</p>
254
+ @endeach
255
+
256
+ @forelse (name in [])
257
+ <li>{{ name }}</li>
258
+ @empty
259
+ <p>No names</p>
260
+ @endforelse
261
+
262
+ @eachelse (user in users)
263
+ <li>{{ user.name }}</li>
264
+ @empty
265
+ <p>No users</p>
266
+ @endeachelse
267
+
268
+ @while (true)
269
+ <p>I'm looping forever.</p>
270
+ @endwhile
271
+ ```
272
+
273
+ > [!NOTE]
274
+ > While iterating through a `foreach` loop, you may use the [loop variable](#the-loop-variable) to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop.
275
+
276
+ When using loops you may also skip the current iteration or end the loop using the `@next` and `@break` directives:
277
+
278
+ ```blade
279
+ for (user in users)
280
+ @if (user.type == 1)
281
+ @continue
282
+ @endif
283
+
284
+ <li>{{ user.name }}</li>
285
+
286
+ @if (user.number == 5)
287
+ @break
288
+ @endif
289
+ @endfor
290
+ ```
291
+
292
+ You may also include the continuation or break condition within the directive declaration:
293
+
294
+ **TODO check this works with and without condition**
295
+ ```blade
296
+ @foreach ($users as $user)
297
+ @continue($user->type == 1)
298
+
299
+ <li>{{ $user->name }}</li>
300
+
301
+ @break($user->number == 5)
302
+ @endforeach
303
+ ```
304
+
305
+ <a name="the-loop-variable"></a>
306
+ ### The Loop Variable
307
+ **TODO can/should we add this?**
308
+ 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:
309
+
310
+ ```blade
311
+ @foreach ($users as $user)
312
+ @if ($loop->first)
313
+ This is the first iteration.
314
+ @endif
315
+
316
+ @if ($loop->last)
317
+ This is the last iteration.
318
+ @endif
319
+
320
+ <p>This is user {{ $user->id }}</p>
321
+ @endforeach
322
+ ```
323
+
324
+ If you are in a nested loop, you may access the parent loop's `$loop` variable via the `parent` property:
325
+
326
+ ```blade
327
+ @foreach ($users as $user)
328
+ @foreach ($user->posts as $post)
329
+ @if ($loop->parent->first)
330
+ This is the first iteration of the parent loop.
331
+ @endif
332
+ @endforeach
333
+ @endforeach
334
+ ```
335
+
336
+ The `$loop` variable also contains a variety of other useful properties:
337
+
338
+ <div class="overflow-auto">
339
+
340
+ | Property | Description |
341
+ | ------------------ | ------------------------------------------------------ |
342
+ | `$loop->index` | The index of the current loop iteration (starts at 0). |
343
+ | `$loop->iteration` | The current loop iteration (starts at 1). |
344
+ | `$loop->remaining` | The iterations remaining in the loop. |
345
+ | `$loop->count` | The total number of items in the array being iterated. |
346
+ | `$loop->first` | Whether this is the first iteration through the loop. |
347
+ | `$loop->last` | Whether this is the last iteration through the loop. |
348
+ | `$loop->even` | Whether this is an even iteration through the loop. |
349
+ | `$loop->odd` | Whether this is an odd iteration through the loop. |
350
+ | `$loop->depth` | The nesting level of the current loop. |
351
+ | `$loop->parent` | When in a nested loop, the parent's loop variable. |
352
+
353
+ </div>
354
+
355
+ ** TODO from here **
356
+
357
+ <a name="conditional-classes"></a>
358
+ ### Conditional Classes & Styles
359
+
360
+ 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:
361
+
362
+ ```blade
363
+ @php
364
+ $isActive = false;
365
+ $hasError = true;
366
+ @endphp
367
+
368
+ <span @class([
369
+ 'p-4',
370
+ 'font-bold' => $isActive,
371
+ 'text-gray-500' => ! $isActive,
372
+ 'bg-red' => $hasError,
373
+ ])></span>
374
+
375
+ <span class="p-4 text-gray-500 bg-red"></span>
376
+ ```
377
+
378
+ Likewise, the `@style` directive may be used to conditionally add inline CSS styles to an HTML element:
379
+
380
+ ```blade
381
+ @php
382
+ $isActive = true;
383
+ @endphp
384
+
385
+ <span @style([
386
+ 'background-color: red',
387
+ 'font-weight: bold' => $isActive,
388
+ ])></span>
389
+
390
+ <span style="background-color: red; font-weight: bold;"></span>
391
+ ```
392
+
393
+ <a name="additional-attributes"></a>
394
+ ### Additional Attributes
395
+
396
+ 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`:
397
+
398
+ ```blade
399
+ <input type="checkbox"
400
+ name="active"
401
+ value="active"
402
+ @checked(old('active', $user->active)) />
403
+ ```
404
+
405
+ Likewise, the `@selected` directive may be used to indicate if a given select option should be "selected":
406
+
407
+ ```blade
408
+ <select name="version">
409
+ @foreach ($product->versions as $version)
410
+ <option value="{{ $version }}" @selected(old('version') == $version)>
411
+ {{ $version }}
412
+ </option>
413
+ @endforeach
414
+ </select>
415
+ ```
416
+
417
+ Additionally, the `@disabled` directive may be used to indicate if a given element should be "disabled":
418
+
419
+ ```blade
420
+ <button type="submit" @disabled($errors->isNotEmpty())>Submit</button>
421
+ ```
422
+
423
+ Moreover, the `@readonly` directive may be used to indicate if a given element should be "readonly":
424
+
425
+ ```blade
426
+ <input type="email"
427
+ name="email"
428
+ value="email@laravel.com"
429
+ @readonly($user->isNotAdmin()) />
430
+ ```
431
+
432
+ In addition, the `@required` directive may be used to indicate if a given element should be "required":
433
+
434
+ ```blade
435
+ <input type="text"
436
+ name="title"
437
+ value="title"
438
+ @required($user->isAdmin()) />
439
+ ```
440
+
441
+ <a name="including-subviews"></a>
442
+ ### Including Subviews
443
+
444
+ > [!NOTE]
445
+ > While you're free to use the `@include` directive, Blade [components](#components) provide similar functionality and offer several benefits over the `@include` directive such as data and attribute binding.
446
+
447
+ Blade's `@include` directive allows you to include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view:
448
+
449
+ ```blade
450
+ <div>
451
+ @include('shared.errors')
452
+
453
+ <form>
454
+ <!-- Form Contents -->
455
+ </form>
456
+ </div>
457
+ ```
458
+
459
+ Even though the included view will inherit all data available in the parent view, you may also pass an array of additional data that should be made available to the included view:
460
+
461
+ ```blade
462
+ @include('view.name', ['status' => 'complete'])
463
+ ```
464
+
465
+ If you attempt to `@include` a view which does not exist, Laravel will throw an error. If you would like to include a view that may or may not be present, you should use the `@includeIf` directive:
466
+
467
+ ```blade
468
+ @includeIf('view.name', ['status' => 'complete'])
469
+ ```
470
+
471
+ If you would like to `@include` a view if a given boolean expression evaluates to `true` or `false`, you may use the `@includeWhen` and `@includeUnless` directives:
472
+
473
+ ```blade
474
+ @includeWhen($boolean, 'view.name', ['status' => 'complete'])
475
+
476
+ @includeUnless($boolean, 'view.name', ['status' => 'complete'])
477
+ ```
478
+
479
+ To include the first view that exists from a given array of views, you may use the `includeFirst` directive:
480
+
481
+ ```blade
482
+ @includeFirst(['custom.admin', 'admin'], ['status' => 'complete'])
483
+ ```
484
+
485
+ > [!WARNING]
486
+ > You should avoid using the `__DIR__` and `__FILE__` constants in your Blade views, since they will refer to the location of the cached, compiled view.
487
+
488
+ <a name="rendering-views-for-collections"></a>
489
+ #### Rendering Views for Collections
490
+
491
+ You may combine loops and includes into one line with Blade's `@each` directive:
492
+
493
+ ```blade
494
+ @each('view.name', $jobs, 'job')
495
+ ```
496
+
497
+ The `@each` directive's first argument is the view to render for each element in the array or collection. The second argument is the array or collection you wish to iterate over, while the third argument is the variable name that will be assigned to the current iteration within the view. So, for example, if you are iterating over an array of `jobs`, typically you will want to access each job as a `job` variable within the view. The array key for the current iteration will be available as the `key` variable within the view.
498
+
499
+ You may also pass a fourth argument to the `@each` directive. This argument determines the view that will be rendered if the given array is empty.
500
+
501
+ ```blade
502
+ @each('view.name', $jobs, 'job', 'view.empty')
503
+ ```
504
+
505
+ > [!WARNING]
506
+ > Views rendered via `@each` do not inherit the variables from the parent view. If the child view requires these variables, you should use the `@foreach` and `@include` directives instead.
507
+
508
+ <a name="the-once-directive"></a>
509
+ ### The `@once` Directive
510
+
511
+ 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](#stacks). For example, if you are rendering a given [component](#components) within a loop, you may wish to only push the JavaScript to the header the first time the component is rendered:
512
+
513
+ ```blade
514
+ @once
515
+ @push('scripts')
516
+ <script>
517
+ // Your custom JavaScript...
518
+ </script>
519
+ @endpush
520
+ @endonce
521
+ ```
522
+
523
+ 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:
524
+
525
+ ```blade
526
+ @pushOnce('scripts')
527
+ <script>
528
+ // Your custom JavaScript...
529
+ </script>
530
+ @endPushOnce
531
+ ```
532
+
533
+ <a name="raw-php"></a>
534
+ ### Raw PHP
535
+
536
+ In some situations, it's useful to embed PHP code into your views. You can use the Blade `@php` directive to execute a block of plain PHP within your template:
537
+
538
+ ```blade
539
+ @php
540
+ $counter = 1;
541
+ @endphp
542
+ ```
543
+
544
+ Or, if you only need to use PHP to import a class, you may use the `@use` directive:
545
+
546
+ ```blade
547
+ @use('App\Models\Flight')
548
+ ```
549
+
550
+ A second argument may be provided to the `@use` directive to alias the imported class:
551
+
552
+ ```php
553
+ @use('App\Models\Flight', 'FlightModel')
554
+ ```
555
+
556
+ <a name="comments"></a>
557
+ ### Comments
558
+
559
+ Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application:
560
+
561
+ ```blade
562
+ {{-- This comment will not be present in the rendered HTML --}}
563
+ ```
564
+
565
+ <a name="components"></a>
566
+ ## Components
567
+
568
+ Components and slots provide similar benefits to sections, layouts, and includes; however, some may find the mental model of components and slots easier to understand. There are two approaches to writing components: class based components and anonymous components.
569
+
570
+ To create a class based component, you may use the `make:component` Artisan command. To illustrate how to use components, we will create a simple `Alert` component. The `make:component` command will place the component in the `app/View/Components` directory:
571
+
572
+ ```shell
573
+ php artisan make:component Alert
574
+ ```
575
+
576
+ The `make:component` command will also create a view template for the component. The view will be placed in the `resources/views/components` directory. When writing components for your own application, components are automatically discovered within the `app/View/Components` directory and `resources/views/components` directory, so no further component registration is typically required.
577
+
578
+ You may also create components within subdirectories:
579
+
580
+ ```shell
581
+ php artisan make:component Forms/Input
582
+ ```
583
+
584
+ The command above will create an `Input` component in the `app/View/Components/Forms` directory and the view will be placed in the `resources/views/components/forms` directory.
585
+
586
+ If you would like to create an anonymous component (a component with only a Blade template and no class), you may use the `--view` flag when invoking the `make:component` command:
587
+
588
+ ```shell
589
+ php artisan make:component forms.input --view
590
+ ```
591
+
592
+ The command above will create a Blade file at `resources/views/components/forms/input.blade.php` which can be rendered as a component via `<x-forms.input />`.
593
+
594
+ <a name="manually-registering-package-components"></a>
595
+ #### Manually Registering Package Components
596
+
597
+ When writing components for your own application, components are automatically discovered within the `app/View/Components` directory and `resources/views/components` directory.
598
+
599
+ However, if you are building a package that utilizes Blade components, you will need to manually register your component class and its HTML tag alias. You should typically register your components in the `boot` method of your package's service provider:
600
+
601
+ use Illuminate\Support\Facades\Blade;
602
+
603
+ /**
604
+ * Bootstrap your package's services.
605
+ */
606
+ public function boot(): void
607
+ {
608
+ Blade::component('package-alert', Alert::class);
609
+ }
610
+
611
+ Once your component has been registered, it may be rendered using its tag alias:
612
+
613
+ ```blade
614
+ <x-package-alert/>
615
+ ```
616
+
617
+ Alternatively, you may use the `componentNamespace` method to autoload component classes by convention. For example, a `Nightshade` package might have `Calendar` and `ColorPicker` components that reside within the `Package\Views\Components` namespace:
618
+
619
+ use Illuminate\Support\Facades\Blade;
620
+
621
+ /**
622
+ * Bootstrap your package's services.
623
+ */
624
+ public function boot(): void
625
+ {
626
+ Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade');
627
+ }
628
+
629
+ This will allow the usage of package components by their vendor namespace using the `package-name::` syntax:
630
+
631
+ ```blade
632
+ <x-nightshade::calendar />
633
+ <x-nightshade::color-picker />
634
+ ```
635
+
636
+ Blade will automatically detect the class that's linked to this component by pascal-casing the component name. Subdirectories are also supported using "dot" notation.
637
+
638
+ <a name="rendering-components"></a>
639
+ ### Rendering Components
640
+
641
+ 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:
642
+
643
+ ```blade
644
+ <x-alert/>
645
+
646
+ <x-user-profile/>
647
+ ```
648
+
649
+ If the component class is nested deeper within the `app/View/Components` directory, you may use the `.` character to indicate directory nesting. For example, if we assume a component is located at `app/View/Components/Inputs/Button.php`, we may render it like so:
650
+
651
+ ```blade
652
+ <x-inputs.button/>
653
+ ```
654
+
655
+ If you would like to conditionally render your component, you may define a `shouldRender` method on your component class. If the `shouldRender` method returns `false` the component will not be rendered:
656
+
657
+ use Illuminate\Support\Str;
658
+
659
+ /**
660
+ * Whether the component should be rendered
661
+ */
662
+ public function shouldRender(): bool
663
+ {
664
+ return Str::length($this->message) > 0;
665
+ }
666
+
667
+ <a name="passing-data-to-components"></a>
668
+ ### Passing Data to Components
669
+
670
+ You may pass data to Blade components using HTML attributes. Hard-coded, primitive values may be passed to the component using simple HTML attribute strings. PHP expressions and variables should be passed to the component via attributes that use the `:` character as a prefix:
671
+
672
+ ```blade
673
+ <x-alert type="error" :message="$message"/>
674
+ ```
675
+
676
+ You should define all of the component's data attributes in its class constructor. All public properties on a component will automatically be made available to the component's view. It is not necessary to pass the data to the view from the component's `render` method:
677
+
678
+ <?php
679
+
680
+ namespace App\View\Components;
681
+
682
+ use Illuminate\View\Component;
683
+ use Illuminate\View\View;
684
+
685
+ class Alert extends Component
686
+ {
687
+ /**
688
+ * Create the component instance.
689
+ */
690
+ public function __construct(
691
+ public string $type,
692
+ public string $message,
693
+ ) {}
694
+
695
+ /**
696
+ * Get the view / contents that represent the component.
697
+ */
698
+ public function render(): View
699
+ {
700
+ return view('components.alert');
701
+ }
702
+ }
703
+
704
+ When your component is rendered, you may display the contents of your component's public variables by echoing the variables by name:
705
+
706
+ ```blade
707
+ <div class="alert alert-{{ $type }}">
708
+ {{ $message }}
709
+ </div>
710
+ ```
711
+
712
+ <a name="casing"></a>
713
+ #### Casing
714
+
715
+ Component constructor arguments should be specified using `camelCase`, while `kebab-case` should be used when referencing the argument names in your HTML attributes. For example, given the following component constructor:
716
+
717
+ /**
718
+ * Create the component instance.
719
+ */
720
+ public function __construct(
721
+ public string $alertType,
722
+ ) {}
723
+
724
+ The `$alertType` argument may be provided to the component like so:
725
+
726
+ ```blade
727
+ <x-alert alert-type="danger" />
728
+ ```
729
+
730
+ <a name="short-attribute-syntax"></a>
731
+ #### Short Attribute Syntax
732
+
733
+ 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:
734
+
735
+ ```blade
736
+ {{-- Short attribute syntax... --}}
737
+ <x-profile :$userId :$name />
738
+
739
+ {{-- Is equivalent to... --}}
740
+ <x-profile :user-id="$userId" :name="$name" />
741
+ ```
742
+
743
+ <a name="escaping-attribute-rendering"></a>
744
+ #### Escaping Attribute Rendering
745
+
746
+ Since some JavaScript frameworks such as Alpine.js also use colon-prefixed attributes, you may use a double colon (`::`) prefix to inform Blade that the attribute is not a PHP expression. For example, given the following component:
747
+
748
+ ```blade
749
+ <x-button ::class="{ danger: isDeleting }">
750
+ Submit
751
+ </x-button>
752
+ ```
753
+
754
+ The following HTML will be rendered by Blade:
755
+
756
+ ```blade
757
+ <button :class="{ danger: isDeleting }">
758
+ Submit
759
+ </button>
760
+ ```
761
+
762
+ <a name="component-methods"></a>
763
+ #### Component Methods
764
+
765
+ In addition to public variables being available to your component template, any public methods on the component may be invoked. For example, imagine a component that has an `isSelected` method:
766
+
767
+ /**
768
+ * Determine if the given option is the currently selected option.
769
+ */
770
+ public function isSelected(string $option): bool
771
+ {
772
+ return $option === $this->selected;
773
+ }
774
+
775
+ You may execute this method from your component template by invoking the variable matching the name of the method:
776
+
777
+ ```blade
778
+ <option {{ $isSelected($value) ? 'selected' : '' }} value="{{ $value }}">
779
+ {{ $label }}
780
+ </option>
781
+ ```
782
+
783
+ <a name="using-attributes-slots-within-component-class"></a>
784
+ #### Accessing Attributes and Slots Within Component Classes
785
+
786
+ Blade components also allow you to access the component name, attributes, and slot inside the class's render method. However, in order to access this data, you should return a closure from your component's `render` method. The closure will receive a `$data` array as its only argument. This array will contain several elements that provide information about the component:
787
+
788
+ use Closure;
789
+
790
+ /**
791
+ * Get the view / contents that represent the component.
792
+ */
793
+ public function render(): Closure
794
+ {
795
+ return function (array $data) {
796
+ // $data['componentName'];
797
+ // $data['attributes'];
798
+ // $data['slot'];
799
+
800
+ return '<div>Components content</div>';
801
+ };
802
+ }
803
+
804
+ The `componentName` is equal to the name used in the HTML tag after the `x-` prefix. So `<x-alert />`'s `componentName` will be `alert`. The `attributes` element will contain all of the attributes that were present on the HTML tag. The `slot` element is an `Illuminate\Support\HtmlString` instance with the contents of the component's slot.
805
+
806
+ The closure should return a string. If the returned string corresponds to an existing view, that view will be rendered; otherwise, the returned string will be evaluated as an inline Blade view.
807
+
808
+ <a name="additional-dependencies"></a>
809
+ #### Additional Dependencies
810
+
811
+ If your component requires dependencies from Laravel's [service container](/docs/{{version}}/container), you may list them before any of the component's data attributes and they will automatically be injected by the container:
812
+
813
+ ```php
814
+ use App\Services\AlertCreator;
815
+
816
+ /**
817
+ * Create the component instance.
818
+ */
819
+ public function __construct(
820
+ public AlertCreator $creator,
821
+ public string $type,
822
+ public string $message,
823
+ ) {}
824
+ ```
825
+
826
+ <a name="hiding-attributes-and-methods"></a>
827
+ #### Hiding Attributes / Methods
828
+
829
+ If you would like to prevent some public methods or properties from being exposed as variables to your component template, you may add them to an `$except` array property on your component:
830
+
831
+ <?php
832
+
833
+ namespace App\View\Components;
834
+
835
+ use Illuminate\View\Component;
836
+
837
+ class Alert extends Component
838
+ {
839
+ /**
840
+ * The properties / methods that should not be exposed to the component template.
841
+ *
842
+ * @var array
843
+ */
844
+ protected $except = ['type'];
845
+
846
+ /**
847
+ * Create the component instance.
848
+ */
849
+ public function __construct(
850
+ public string $type,
851
+ ) {}
852
+ }
853
+
854
+ <a name="component-attributes"></a>
855
+ ### Component Attributes
856
+
857
+ 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:
858
+
859
+ ```blade
860
+ <x-alert type="error" :message="$message" class="mt-4"/>
861
+ ```
862
+
863
+ All of the attributes that are not part of the component's constructor will automatically be added to the component's "attribute bag". This attribute bag is automatically made available to the component via the `$attributes` variable. All of the attributes may be rendered within the component by echoing this variable:
864
+
865
+ ```blade
866
+ <div {{ $attributes }}>
867
+ <!-- Component content -->
868
+ </div>
869
+ ```
870
+
871
+ > [!WARNING]
872
+ > Using directives such as `@env` within component tags is not supported at this time. For example, `<x-alert :live="@env('production')"/>` will not be compiled.
873
+
874
+ <a name="default-merged-attributes"></a>
875
+ #### Default / Merged Attributes
876
+
877
+ 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 bag's `merge` method. This method is particularly useful for defining a set of default CSS classes that should always be applied to a component:
878
+
879
+ ```blade
880
+ <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
881
+ {{ $message }}
882
+ </div>
883
+ ```
884
+
885
+ If we assume this component is utilized like so:
886
+
887
+ ```blade
888
+ <x-alert type="error" :message="$message" class="mb-4"/>
889
+ ```
890
+
891
+ The final, rendered HTML of the component will appear like the following:
892
+
893
+ ```blade
894
+ <div class="alert alert-error mb-4">
895
+ <!-- Contents of the $message variable -->
896
+ </div>
897
+ ```
898
+
899
+ <a name="conditionally-merge-classes"></a>
900
+ #### Conditionally Merge Classes
901
+
902
+ 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:
903
+
904
+ ```blade
905
+ <div {{ $attributes->class(['p-4', 'bg-red' => $hasError]) }}>
906
+ {{ $message }}
907
+ </div>
908
+ ```
909
+
910
+ If you need to merge other attributes onto your component, you can chain the `merge` method onto the `class` method:
911
+
912
+ ```blade
913
+ <button {{ $attributes->class(['p-4'])->merge(['type' => 'button']) }}>
914
+ {{ $slot }}
915
+ </button>
916
+ ```
917
+
918
+ > [!NOTE]
919
+ > If you need to conditionally compile classes on other HTML elements that shouldn't receive merged attributes, you can use the [`@class` directive](#conditional-classes).
920
+
921
+ <a name="non-class-attribute-merging"></a>
922
+ #### Non-Class Attribute Merging
923
+
924
+ When merging attributes that are not `class` attributes, the values provided to the `merge` method will be considered the "default" values of the attribute. However, unlike the `class` attribute, these attributes will not be merged with injected attribute values. Instead, they will be overwritten. For example, a `button` component's implementation may look like the following:
925
+
926
+ ```blade
927
+ <button {{ $attributes->merge(['type' => 'button']) }}>
928
+ {{ $slot }}
929
+ </button>
930
+ ```
931
+
932
+ To render the button component with a custom `type`, it may be specified when consuming the component. If no type is specified, the `button` type will be used:
933
+
934
+ ```blade
935
+ <x-button type="submit">
936
+ Submit
937
+ </x-button>
938
+ ```
939
+
940
+ The rendered HTML of the `button` component in this example would be:
941
+
942
+ ```blade
943
+ <button type="submit">
944
+ Submit
945
+ </button>
946
+ ```
947
+
948
+ If you would like an attribute other than `class` to have its default value and injected values joined together, you may 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:
949
+
950
+ ```blade
951
+ <div {{ $attributes->merge(['data-controller' => $attributes->prepends('profile-controller')]) }}>
952
+ {{ $slot }}
953
+ </div>
954
+ ```
955
+
956
+ <a name="filtering-attributes"></a>
957
+ #### Retrieving and Filtering Attributes
958
+
959
+ 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:
960
+
961
+ ```blade
962
+ {{ $attributes->filter(fn (string $value, string $key) => $key == 'foo') }}
963
+ ```
964
+
965
+ For convenience, you may use the `whereStartsWith` method to retrieve all attributes whose keys begin with a given string:
966
+
967
+ ```blade
968
+ {{ $attributes->whereStartsWith('wire:model') }}
969
+ ```
970
+
971
+ Conversely, the `whereDoesntStartWith` method may be used to exclude all attributes whose keys begin with a given string:
972
+
973
+ ```blade
974
+ {{ $attributes->whereDoesntStartWith('wire:model') }}
975
+ ```
976
+
977
+ Using the `first` method, you may render the first attribute in a given attribute bag:
978
+
979
+ ```blade
980
+ {{ $attributes->whereStartsWith('wire:model')->first() }}
981
+ ```
982
+
983
+ 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:
984
+
985
+ ```blade
986
+ @if ($attributes->has('class'))
987
+ <div>Class attribute is present</div>
988
+ @endif
989
+ ```
990
+
991
+ If an array is passed to the `has` method, the method will determine if all of the given attributes are present on the component:
992
+
993
+ ```blade
994
+ @if ($attributes->has(['name', 'class']))
995
+ <div>All of the attributes are present</div>
996
+ @endif
997
+ ```
998
+
999
+ The `hasAny` method may be used to determine if any of the given attributes are present on the component:
1000
+
1001
+ ```blade
1002
+ @if ($attributes->hasAny(['href', ':href', 'v-bind:href']))
1003
+ <div>One of the attributes is present</div>
1004
+ @endif
1005
+ ```
1006
+
1007
+ You may retrieve a specific attribute's value using the `get` method:
1008
+
1009
+ ```blade
1010
+ {{ $attributes->get('class') }}
1011
+ ```
1012
+
1013
+ <a name="reserved-keywords"></a>
1014
+ ### Reserved Keywords
1015
+
1016
+ By default, some keywords are reserved for Blade's internal use in order to render components. The following keywords cannot be defined as public properties or method names within your components:
1017
+
1018
+ <div class="content-list" markdown="1">
1019
+
1020
+ - `data`
1021
+ - `render`
1022
+ - `resolveView`
1023
+ - `shouldRender`
1024
+ - `view`
1025
+ - `withAttributes`
1026
+ - `withName`
1027
+
1028
+ </div>
1029
+
1030
+ <a name="slots"></a>
1031
+ ### Slots
1032
+
1033
+ You will often need to pass additional content to your component via "slots". Component slots are rendered by echoing the `$slot` variable. To explore this concept, let's imagine that an `alert` component has the following markup:
1034
+
1035
+ ```blade
1036
+ <!-- /resources/views/components/alert.blade.php -->
1037
+
1038
+ <div class="alert alert-danger">
1039
+ {{ $slot }}
1040
+ </div>
1041
+ ```
1042
+
1043
+ We may pass content to the `slot` by injecting content into the component:
1044
+
1045
+ ```blade
1046
+ <x-alert>
1047
+ <strong>Whoops!</strong> Something went wrong!
1048
+ </x-alert>
1049
+ ```
1050
+
1051
+ 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:
1052
+
1053
+ ```blade
1054
+ <!-- /resources/views/components/alert.blade.php -->
1055
+
1056
+ <span class="alert-title">{{ $title }}</span>
1057
+
1058
+ <div class="alert alert-danger">
1059
+ {{ $slot }}
1060
+ </div>
1061
+ ```
1062
+
1063
+ 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:
1064
+
1065
+ ```xml
1066
+ <x-alert>
1067
+ <x-slot:title>
1068
+ Server Error
1069
+ </x-slot>
1070
+
1071
+ <strong>Whoops!</strong> Something went wrong!
1072
+ </x-alert>
1073
+ ```
1074
+
1075
+ You may invoke a slot's `isEmpty` method to determine if the slot contains content:
1076
+
1077
+ ```blade
1078
+ <span class="alert-title">{{ $title }}</span>
1079
+
1080
+ <div class="alert alert-danger">
1081
+ @if ($slot->isEmpty())
1082
+ This is default content if the slot is empty.
1083
+ @else
1084
+ {{ $slot }}
1085
+ @endif
1086
+ </div>
1087
+ ```
1088
+
1089
+ Additionally, the `hasActualContent` method may be used to determine if the slot contains any "actual" content that is not an HTML comment:
1090
+
1091
+ ```blade
1092
+ @if ($slot->hasActualContent())
1093
+ The scope has non-comment content.
1094
+ @endif
1095
+ ```
1096
+
1097
+ <a name="scoped-slots"></a>
1098
+ #### Scoped Slots
1099
+
1100
+ 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:
1101
+
1102
+ ```blade
1103
+ <x-alert>
1104
+ <x-slot:title>
1105
+ {{ $component->formatAlert('Server Error') }}
1106
+ </x-slot>
1107
+
1108
+ <strong>Whoops!</strong> Something went wrong!
1109
+ </x-alert>
1110
+ ```
1111
+
1112
+ <a name="slot-attributes"></a>
1113
+ #### Slot Attributes
1114
+
1115
+ Like Blade components, you may assign additional [attributes](#component-attributes) to slots such as CSS class names:
1116
+
1117
+ ```xml
1118
+ <x-card class="shadow-sm">
1119
+ <x-slot:heading class="font-bold">
1120
+ Heading
1121
+ </x-slot>
1122
+
1123
+ Content
1124
+
1125
+ <x-slot:footer class="text-sm">
1126
+ Footer
1127
+ </x-slot>
1128
+ </x-card>
1129
+ ```
1130
+
1131
+ 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](#component-attributes):
1132
+
1133
+ ```blade
1134
+ @props([
1135
+ 'heading',
1136
+ 'footer',
1137
+ ])
1138
+
1139
+ <div {{ $attributes->class(['border']) }}>
1140
+ <h1 {{ $heading->attributes->class(['text-lg']) }}>
1141
+ {{ $heading }}
1142
+ </h1>
1143
+
1144
+ {{ $slot }}
1145
+
1146
+ <footer {{ $footer->attributes->class(['text-gray-700']) }}>
1147
+ {{ $footer }}
1148
+ </footer>
1149
+ </div>
1150
+ ```
1151
+
1152
+ <a name="inline-component-views"></a>
1153
+ ### Inline Component Views
1154
+
1155
+ For very small components, it may feel cumbersome to manage both the component class and the component's view template. For this reason, you may return the component's markup directly from the `render` method:
1156
+
1157
+ /**
1158
+ * Get the view / contents that represent the component.
1159
+ */
1160
+ public function render(): string
1161
+ {
1162
+ return <<<'blade'
1163
+ <div class="alert alert-danger">
1164
+ {{ $slot }}
1165
+ </div>
1166
+ blade;
1167
+ }
1168
+
1169
+ <a name="generating-inline-view-components"></a>
1170
+ #### Generating Inline View Components
1171
+
1172
+ To create a component that renders an inline view, you may use the `inline` option when executing the `make:component` command:
1173
+
1174
+ ```shell
1175
+ php artisan make:component Alert --inline
1176
+ ```
1177
+
1178
+ <a name="dynamic-components"></a>
1179
+ ### Dynamic Components
1180
+
1181
+ Sometimes you may need to render a component but not know which component should be rendered until runtime. In this situation, you may use Laravel's built-in `dynamic-component` component to render the component based on a runtime value or variable:
1182
+
1183
+ ```blade
1184
+ // $componentName = "secondary-button";
1185
+
1186
+ <x-dynamic-component :component="$componentName" class="mt-4" />
1187
+ ```
1188
+
1189
+ <a name="manually-registering-components"></a>
1190
+ ### Manually Registering Components
1191
+
1192
+ > [!WARNING]
1193
+ > 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.
1194
+
1195
+ When writing components for your own application, components are automatically discovered within the `app/View/Components` directory and `resources/views/components` directory.
1196
+
1197
+ 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:
1198
+
1199
+ use Illuminate\Support\Facades\Blade;
1200
+ use VendorPackage\View\Components\AlertComponent;
1201
+
1202
+ /**
1203
+ * Bootstrap your package's services.
1204
+ */
1205
+ public function boot(): void
1206
+ {
1207
+ Blade::component('package-alert', AlertComponent::class);
1208
+ }
1209
+
1210
+ Once your component has been registered, it may be rendered using its tag alias:
1211
+
1212
+ ```blade
1213
+ <x-package-alert/>
1214
+ ```
1215
+
1216
+ #### Autoloading Package Components
1217
+
1218
+ Alternatively, you may use the `componentNamespace` method to autoload component classes by convention. For example, a `Nightshade` package might have `Calendar` and `ColorPicker` components that reside within the `Package\Views\Components` namespace:
1219
+
1220
+ use Illuminate\Support\Facades\Blade;
1221
+
1222
+ /**
1223
+ * Bootstrap your package's services.
1224
+ */
1225
+ public function boot(): void
1226
+ {
1227
+ Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade');
1228
+ }
1229
+
1230
+ This will allow the usage of package components by their vendor namespace using the `package-name::` syntax:
1231
+
1232
+ ```blade
1233
+ <x-nightshade::calendar />
1234
+ <x-nightshade::color-picker />
1235
+ ```
1236
+
1237
+ Blade will automatically detect the class that's linked to this component by pascal-casing the component name. Subdirectories are also supported using "dot" notation.
1238
+
1239
+ <a name="anonymous-components"></a>
1240
+ ## Anonymous Components
1241
+
1242
+ Similar to inline components, anonymous components provide a mechanism for managing a component via a single file. However, anonymous components utilize a single view file and have no associated class. To define an anonymous component, you only need to place a Blade template within your `resources/views/components` directory. For example, assuming you have defined a component at `resources/views/components/alert.blade.php`, you may simply render it like so:
1243
+
1244
+ ```blade
1245
+ <x-alert/>
1246
+ ```
1247
+
1248
+ You may use the `.` character to indicate if a component is nested deeper inside the `components` directory. For example, assuming the component is defined at `resources/views/components/inputs/button.blade.php`, you may render it like so:
1249
+
1250
+ ```blade
1251
+ <x-inputs.button/>
1252
+ ```
1253
+
1254
+ <a name="anonymous-index-components"></a>
1255
+ ### Anonymous Index Components
1256
+
1257
+ Sometimes, when a component is made up of many Blade templates, you may wish to group the given component's templates within a single directory. For example, imagine an "accordion" component with the following directory structure:
1258
+
1259
+ ```none
1260
+ /resources/views/components/accordion.blade.php
1261
+ /resources/views/components/accordion/item.blade.php
1262
+ ```
1263
+
1264
+ This directory structure allows you to render the accordion component and its item like so:
1265
+
1266
+ ```blade
1267
+ <x-accordion>
1268
+ <x-accordion.item>
1269
+ ...
1270
+ </x-accordion.item>
1271
+ </x-accordion>
1272
+ ```
1273
+
1274
+ However, in order to render the accordion component via `x-accordion`, we were forced to place the "index" accordion component template in the `resources/views/components` directory instead of nesting it within the `accordion` directory with the other accordion related templates.
1275
+
1276
+ Thankfully, Blade allows you to place an `index.blade.php` file within a component's template directory. When an `index.blade.php` template exists for the component, it will be rendered as the "root" node of the component. So, we can continue to use the same Blade syntax given in the example above; however, we will adjust our directory structure like so:
1277
+
1278
+ ```none
1279
+ /resources/views/components/accordion/index.blade.php
1280
+ /resources/views/components/accordion/item.blade.php
1281
+ ```
1282
+
1283
+ <a name="data-properties-attributes"></a>
1284
+ ### Data Properties / Attributes
1285
+
1286
+ Since anonymous components do not have any associated class, you may wonder how you may differentiate which data should be passed to the component as variables and which attributes should be placed in the component's [attribute bag](#component-attributes).
1287
+
1288
+ You may specify which attributes should be considered data variables using the `@props` directive at the top of your component's Blade template. All other attributes on the component will be available via the component's attribute bag. If you wish to give a data variable a default value, you may specify the variable's name as the array key and the default value as the array value:
1289
+
1290
+ ```blade
1291
+ <!-- /resources/views/components/alert.blade.php -->
1292
+
1293
+ @props(['type' => 'info', 'message'])
1294
+
1295
+ <div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
1296
+ {{ $message }}
1297
+ </div>
1298
+ ```
1299
+
1300
+ Given the component definition above, we may render the component like so:
1301
+
1302
+ ```blade
1303
+ <x-alert type="error" :message="$message" class="mb-4"/>
1304
+ ```
1305
+
1306
+ <a name="accessing-parent-data"></a>
1307
+ ### Accessing Parent Data
1308
+
1309
+ 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>`:
1310
+
1311
+ ```blade
1312
+ <x-menu color="purple">
1313
+ <x-menu.item>...</x-menu.item>
1314
+ <x-menu.item>...</x-menu.item>
1315
+ </x-menu>
1316
+ ```
1317
+
1318
+ The `<x-menu>` component may have an implementation like the following:
1319
+
1320
+ ```blade
1321
+ <!-- /resources/views/components/menu/index.blade.php -->
1322
+
1323
+ @props(['color' => 'gray'])
1324
+
1325
+ <ul {{ $attributes->merge(['class' => 'bg-'.$color.'-200']) }}>
1326
+ {{ $slot }}
1327
+ </ul>
1328
+ ```
1329
+
1330
+ 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:
1331
+
1332
+ ```blade
1333
+ <!-- /resources/views/components/menu/item.blade.php -->
1334
+
1335
+ @aware(['color' => 'gray'])
1336
+
1337
+ <li {{ $attributes->merge(['class' => 'text-'.$color.'-800']) }}>
1338
+ {{ $slot }}
1339
+ </li>
1340
+ ```
1341
+
1342
+ > [!WARNING]
1343
+ > The `@aware` directive can not access parent data that is not explicitly passed to the parent component via HTML attributes. Default `@props` values that are not explicitly passed to the parent component can not be accessed by the `@aware` directive.
1344
+
1345
+ <a name="anonymous-component-paths"></a>
1346
+ ### Anonymous Component Paths
1347
+
1348
+ As previously discussed, anonymous components are typically defined by placing a Blade template within your `resources/views/components` directory. However, you may occasionally want to register other anonymous component paths with Laravel in addition to the default path.
1349
+
1350
+ The `anonymousComponentPath` method accepts the "path" to the anonymous component location as its first argument and an optional "namespace" that components should be placed under as its second argument. Typically, this method should be called from the `boot` method of one of your application's [service providers](/docs/{{version}}/providers):
1351
+
1352
+ /**
1353
+ * Bootstrap any application services.
1354
+ */
1355
+ public function boot(): void
1356
+ {
1357
+ Blade::anonymousComponentPath(__DIR__.'/../components');
1358
+ }
1359
+
1360
+ When component paths are registered without a specified prefix as in the example above, they may be rendered in your Blade components without a corresponding prefix as well. For example, if a `panel.blade.php` component exists in the path registered above, it may be rendered like so:
1361
+
1362
+ ```blade
1363
+ <x-panel />
1364
+ ```
1365
+
1366
+ Prefix "namespaces" may be provided as the second argument to the `anonymousComponentPath` method:
1367
+
1368
+ Blade::anonymousComponentPath(__DIR__.'/../components', 'dashboard');
1369
+
1370
+ When a prefix is provided, components within that "namespace" may be rendered by prefixing to the component's namespace to the component name when the component is rendered:
1371
+
1372
+ ```blade
1373
+ <x-dashboard::panel />
1374
+ ```
1375
+
1376
+ <a name="building-layouts"></a>
1377
+ ## Building Layouts
1378
+
1379
+ <a name="layouts-using-components"></a>
1380
+ ### Layouts Using Components
1381
+
1382
+ Most web applications maintain the same general layout across various pages. It would be incredibly cumbersome and hard to maintain our application if we had to repeat the entire layout HTML in every view we create. Thankfully, it's convenient to define this layout as a single [Blade component](#components) and then use it throughout our application.
1383
+
1384
+ <a name="defining-the-layout-component"></a>
1385
+ #### Defining the Layout Component
1386
+
1387
+ For example, imagine we are building a "todo" list application. We might define a `layout` component that looks like the following:
1388
+
1389
+ ```blade
1390
+ <!-- resources/views/components/layout.blade.php -->
1391
+
1392
+ <html>
1393
+ <head>
1394
+ <title>{{ $title ?? 'Todo Manager' }}</title>
1395
+ </head>
1396
+ <body>
1397
+ <h1>Todos</h1>
1398
+ <hr/>
1399
+ {{ $slot }}
1400
+ </body>
1401
+ </html>
1402
+ ```
1403
+
1404
+ <a name="applying-the-layout-component"></a>
1405
+ #### Applying the Layout Component
1406
+
1407
+ Once the `layout` component has been defined, we may create a Blade view that utilizes the component. In this example, we will define a simple view that displays our task list:
1408
+
1409
+ ```blade
1410
+ <!-- resources/views/tasks.blade.php -->
1411
+
1412
+ <x-layout>
1413
+ @foreach ($tasks as $task)
1414
+ {{ $task }}
1415
+ @endforeach
1416
+ </x-layout>
1417
+ ```
1418
+
1419
+ Remember, content that is injected into a component will be supplied to the default `$slot` variable within our `layout` component. As you may have noticed, our `layout` also respects a `$title` slot if one is provided; otherwise, a default title is shown. We may inject a custom title from our task list view using the standard slot syntax discussed in the [component documentation](#components):
1420
+
1421
+ ```blade
1422
+ <!-- resources/views/tasks.blade.php -->
1423
+
1424
+ <x-layout>
1425
+ <x-slot:title>
1426
+ Custom Title
1427
+ </x-slot>
1428
+
1429
+ @foreach ($tasks as $task)
1430
+ {{ $task }}
1431
+ @endforeach
1432
+ </x-layout>
1433
+ ```
1434
+
1435
+ Now that we have defined our layout and task list views, we just need to return the `task` view from a route:
1436
+
1437
+ use App\Models\Task;
1438
+
1439
+ Route::get('/tasks', function () {
1440
+ return view('tasks', ['tasks' => Task::all()]);
1441
+ });
1442
+
1443
+ <a name="layouts-using-template-inheritance"></a>
1444
+ ### Layouts Using Template Inheritance
1445
+
1446
+ <a name="defining-a-layout"></a>
1447
+ #### Defining a Layout
1448
+
1449
+ Layouts may also be created via "template inheritance". This was the primary way of building applications prior to the introduction of [components](#components).
1450
+
1451
+ To get started, let's take a look at a simple example. First, we will examine a page layout. Since most web applications maintain the same general layout across various pages, it's convenient to define this layout as a single Blade view:
1452
+
1453
+ ```blade
1454
+ <!-- resources/views/layouts/app.blade.php -->
1455
+
1456
+ <html>
1457
+ <head>
1458
+ <title>App Name - @yield('title')</title>
1459
+ </head>
1460
+ <body>
1461
+ @section('sidebar')
1462
+ This is the master sidebar.
1463
+ @show
1464
+
1465
+ <div class="container">
1466
+ @yield('content')
1467
+ </div>
1468
+ </body>
1469
+ </html>
1470
+ ```
1471
+
1472
+ As you can see, this file contains typical HTML mark-up. However, take note of the `@section` and `@yield` directives. The `@section` directive, as the name implies, defines a section of content, while the `@yield` directive is used to display the contents of a given section.
1473
+
1474
+ Now that we have defined a layout for our application, let's define a child page that inherits the layout.
1475
+
1476
+ <a name="extending-a-layout"></a>
1477
+ #### Extending a Layout
1478
+
1479
+ When defining a child view, use the `@extends` Blade directive to specify which layout the child view should "inherit". Views which extend a Blade layout may inject content into the layout's sections using `@section` directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using `@yield`:
1480
+
1481
+ ```blade
1482
+ <!-- resources/views/child.blade.php -->
1483
+
1484
+ @extends('layouts.app')
1485
+
1486
+ @section('title', 'Page Title')
1487
+
1488
+ @section('sidebar')
1489
+ @@parent
1490
+
1491
+ <p>This is appended to the master sidebar.</p>
1492
+ @endsection
1493
+
1494
+ @section('content')
1495
+ <p>This is my body content.</p>
1496
+ @endsection
1497
+ ```
1498
+
1499
+ In this example, the `sidebar` section is utilizing the `@@parent` directive to append (rather than overwriting) content to the layout's sidebar. The `@@parent` directive will be replaced by the content of the layout when the view is rendered.
1500
+
1501
+ > [!NOTE]
1502
+ > Contrary to the previous example, this `sidebar` section ends with `@endsection` instead of `@show`. The `@endsection` directive will only define a section while `@show` will define and **immediately yield** the section.
1503
+
1504
+ The `@yield` directive also accepts a default value as its second parameter. This value will be rendered if the section being yielded is undefined:
1505
+
1506
+ ```blade
1507
+ @yield('content', 'Default content')
1508
+ ```
1509
+
1510
+ <a name="forms"></a>
1511
+ ## Forms
1512
+
1513
+ <a name="csrf-field"></a>
1514
+ ### CSRF Field
1515
+
1516
+ 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](/docs/{{version}}/csrf) middleware can validate the request. You may use the `@csrf` Blade directive to generate the token field:
1517
+
1518
+ ```blade
1519
+ <form method="POST" action="/profile">
1520
+ @csrf
1521
+
1522
+ ...
1523
+ </form>
1524
+ ```
1525
+
1526
+ <a name="method-field"></a>
1527
+ ### Method Field
1528
+
1529
+ 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` Blade directive can create this field for you:
1530
+
1531
+ ```blade
1532
+ <form action="/foo/bar" method="POST">
1533
+ @method('PUT')
1534
+
1535
+ ...
1536
+ </form>
1537
+ ```
1538
+
1539
+ <a name="validation-errors"></a>
1540
+ ### Validation Errors
1541
+
1542
+ The `@error` directive may be used to quickly check if [validation error messages](/docs/{{version}}/validation#quick-displaying-the-validation-errors) exist for a given attribute. Within an `@error` directive, you may echo the `$message` variable to display the error message:
1543
+
1544
+ ```blade
1545
+ <!-- /resources/views/post/create.blade.php -->
1546
+
1547
+ <label for="title">Post Title</label>
1548
+
1549
+ <input id="title"
1550
+ type="text"
1551
+ class="@error('title') is-invalid @enderror">
1552
+
1553
+ @error('title')
1554
+ <div class="alert alert-danger">{{ $message }}</div>
1555
+ @enderror
1556
+ ```
1557
+
1558
+ 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:
1559
+
1560
+ ```blade
1561
+ <!-- /resources/views/auth.blade.php -->
1562
+
1563
+ <label for="email">Email address</label>
1564
+
1565
+ <input id="email"
1566
+ type="email"
1567
+ class="@error('email') is-invalid @else is-valid @enderror">
1568
+ ```
1569
+
1570
+ You may pass [the name of a specific error bag](/docs/{{version}}/validation#named-error-bags) as the second parameter to the `@error` directive to retrieve validation error messages on pages containing multiple forms:
1571
+
1572
+ ```blade
1573
+ <!-- /resources/views/auth.blade.php -->
1574
+
1575
+ <label for="email">Email address</label>
1576
+
1577
+ <input id="email"
1578
+ type="email"
1579
+ class="@error('email', 'login') is-invalid @enderror">
1580
+
1581
+ @error('email', 'login')
1582
+ <div class="alert alert-danger">{{ $message }}</div>
1583
+ @enderror
1584
+ ```
1585
+
1586
+ <a name="stacks"></a>
1587
+ ## Stacks
1588
+
1589
+ Blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be particularly useful for specifying any JavaScript libraries required by your child views:
1590
+
1591
+ ```blade
1592
+ @push('scripts')
1593
+ <script src="/example.js"></script>
1594
+ @endpush
1595
+ ```
1596
+
1597
+ If you would like to `@push` content if a given boolean expression evaluates to `true`, you may use the `@pushIf` directive:
1598
+
1599
+ ```blade
1600
+ @pushIf($shouldPush, 'scripts')
1601
+ <script src="/example.js"></script>
1602
+ @endPushIf
1603
+ ```
1604
+
1605
+ 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:
1606
+
1607
+ ```blade
1608
+ <head>
1609
+ <!-- Head Contents -->
1610
+
1611
+ @stack('scripts')
1612
+ </head>
1613
+ ```
1614
+
1615
+ If you would like to prepend content onto the beginning of a stack, you should use the `@prepend` directive:
1616
+
1617
+ ```blade
1618
+ @push('scripts')
1619
+ This will be second...
1620
+ @endpush
1621
+
1622
+ // Later...
1623
+
1624
+ @prepend('scripts')
1625
+ This will be first...
1626
+ @endprepend
1627
+ ```
1628
+
1629
+ <a name="service-injection"></a>
1630
+ ## Service Injection
1631
+
1632
+ The `@inject` directive may be used to retrieve a service from the Laravel [service container](/docs/{{version}}/container). The first argument passed to `@inject` is the name of the variable the service will be placed into, while the second argument is the class or interface name of the service you wish to resolve:
1633
+
1634
+ ```blade
1635
+ @inject('metrics', 'App\Services\MetricsService')
1636
+
1637
+ <div>
1638
+ Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
1639
+ </div>
1640
+ ```
1641
+
1642
+ <a name="rendering-inline-blade-templates"></a>
1643
+ ## Rendering Inline Blade Templates
1644
+
1645
+ Sometimes you may need to transform a raw Blade template string into valid HTML. You may accomplish this using the `render` method provided by the `Blade` facade. The `render` method accepts the Blade template string and an optional array of data to provide to the template:
1646
+
1647
+ ```php
1648
+ use Illuminate\Support\Facades\Blade;
1649
+
1650
+ return Blade::render('Hello, {{ $name }}', ['name' => 'Julian Bashir']);
1651
+ ```
1652
+
1653
+ Laravel renders inline Blade templates by writing them to the `storage/framework/views` directory. If you would like Laravel to remove these temporary files after rendering the Blade template, you may provide the `deleteCachedView` argument to the method:
1654
+
1655
+ ```php
1656
+ return Blade::render(
1657
+ 'Hello, {{ $name }}',
1658
+ ['name' => 'Julian Bashir'],
1659
+ deleteCachedView: true
1660
+ );
1661
+ ```
1662
+
1663
+ <a name="rendering-blade-fragments"></a>
1664
+ ## Rendering Blade Fragments
1665
+
1666
+ When using frontend frameworks such as [Turbo](https://turbo.hotwired.dev/) and [htmx](https://htmx.org/), 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:
1667
+
1668
+ ```blade
1669
+ @fragment('user-list')
1670
+ <ul>
1671
+ @foreach ($users as $user)
1672
+ <li>{{ $user->name }}</li>
1673
+ @endforeach
1674
+ </ul>
1675
+ @endfragment
1676
+ ```
1677
+
1678
+ 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:
1679
+
1680
+ ```php
1681
+ return view('dashboard', ['users' => $users])->fragment('user-list');
1682
+ ```
1683
+
1684
+ 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:
1685
+
1686
+ ```php
1687
+ return view('dashboard', ['users' => $users])
1688
+ ->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
1689
+ ```
1690
+
1691
+ The `fragments` and `fragmentsIf` methods allow you to return multiple view fragments in the response. The fragments will be concatenated together:
1692
+
1693
+ ```php
1694
+ view('dashboard', ['users' => $users])
1695
+ ->fragments(['user-list', 'comment-list']);
1696
+
1697
+ view('dashboard', ['users' => $users])
1698
+ ->fragmentsIf(
1699
+ $request->hasHeader('HX-Request'),
1700
+ ['user-list', 'comment-list']
1701
+ );
1702
+ ```
1703
+
1704
+ <a name="extending-blade"></a>
1705
+ ## Extending Blade
1706
+
1707
+ 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.
1708
+
1709
+ The following example creates a `@datetime($var)` directive which formats a given `$var`, which should be an instance of `DateTime`:
1710
+
1711
+ <?php
1712
+
1713
+ namespace App\Providers;
1714
+
1715
+ use Illuminate\Support\Facades\Blade;
1716
+ use Illuminate\Support\ServiceProvider;
1717
+
1718
+ class AppServiceProvider extends ServiceProvider
1719
+ {
1720
+ /**
1721
+ * Register any application services.
1722
+ */
1723
+ public function register(): void
1724
+ {
1725
+ // ...
1726
+ }
1727
+
1728
+ /**
1729
+ * Bootstrap any application services.
1730
+ */
1731
+ public function boot(): void
1732
+ {
1733
+ Blade::directive('datetime', function (string $expression) {
1734
+ return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
1735
+ });
1736
+ }
1737
+ }
1738
+
1739
+ 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:
1740
+
1741
+ <?php echo ($var)->format('m/d/Y H:i'); ?>
1742
+
1743
+ > [!WARNING]
1744
+ > 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 the `view:clear` Artisan command.
1745
+
1746
+ <a name="custom-echo-handlers"></a>
1747
+ ### Custom Echo Handlers
1748
+
1749
+ If you attempt to "echo" an object using Blade, the object's `__toString` method will be invoked. The [`__toString`](https://www.php.net/manual/en/language.oop5.magic.php#object.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.
1750
+
1751
+ 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:
1752
+
1753
+ use Illuminate\Support\Facades\Blade;
1754
+ use Money\Money;
1755
+
1756
+ /**
1757
+ * Bootstrap any application services.
1758
+ */
1759
+ public function boot(): void
1760
+ {
1761
+ Blade::stringable(function (Money $money) {
1762
+ return $money->formatTo('en_GB');
1763
+ });
1764
+ }
1765
+
1766
+ Once your custom echo handler has been defined, you may simply echo the object in your Blade template:
1767
+
1768
+ ```blade
1769
+ Cost: {{ $money }}
1770
+ ```
1771
+
1772
+ <a name="custom-if-statements"></a>
1773
+ ### Custom If Statements
1774
+
1775
+ 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`:
1776
+
1777
+ use Illuminate\Support\Facades\Blade;
1778
+
1779
+ /**
1780
+ * Bootstrap any application services.
1781
+ */
1782
+ public function boot(): void
1783
+ {
1784
+ Blade::if('disk', function (string $value) {
1785
+ return config('filesystems.default') === $value;
1786
+ });
1787
+ }
1788
+
1789
+ Once the custom conditional has been defined, you can use it within your templates:
1790
+
1791
+ ```blade
1792
+ @disk('local')
1793
+ <!-- The application is using the local disk... -->
1794
+ @elsedisk('s3')
1795
+ <!-- The application is using the s3 disk... -->
1796
+ @else
1797
+ <!-- The application is using some other disk... -->
1798
+ @enddisk
1799
+
1800
+ @unlessdisk('local')
1801
+ <!-- The application is not using the local disk... -->
1802
+ @enddisk
1803
+ ```