rblade 0.2.5 → 0.4.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,1257 @@
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
+
9
+ **TODO redo TOC**
10
+
11
+ <a name="introduction"></a>
12
+ ## Introduction
13
+
14
+ 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.
15
+
16
+ <a name="displaying-data"></a>
17
+ ## Displaying Data
18
+
19
+ 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:
20
+
21
+ ```ruby
22
+ def index
23
+ name = "Samantha"
24
+ end
25
+ ```
26
+
27
+ You may display the contents of the `name` variable like so:
28
+
29
+ ```rblade
30
+ Hello, {{ name }}.
31
+ ```
32
+
33
+ > [!NOTE]
34
+ > RBlade's `{{ }}` echo statements are automatically sent through Rails' `h` function to prevent XSS attacks.
35
+
36
+ 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:
37
+
38
+ ```rblade
39
+ The current UNIX timestamp is {{ Time.now.to_i }}.
40
+ ```
41
+
42
+ <a name="html-entity-encoding"></a>
43
+ ### HTML Entity Encoding
44
+
45
+ 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:
46
+
47
+ ```rblade
48
+ Hello, {!! name !!}.
49
+ ```
50
+
51
+ > [!WARNING]
52
+ > 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.
53
+
54
+ <a name="blade-and-javascript-frameworks"></a>
55
+ ### Blade and JavaScript Frameworks
56
+
57
+ 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:
58
+
59
+ ```rblade
60
+ <h1>Laravel</h1>
61
+
62
+ Hello, @{{ name }}.
63
+ ```
64
+
65
+ 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.
66
+
67
+ The `@` symbol may also be used to escape RBlade directives:
68
+
69
+ ```rblade
70
+ {{-- Blade template --}}
71
+ @@if()
72
+
73
+ <!-- HTML output -->
74
+ @if()
75
+ ```
76
+
77
+ <a name="the-at-verbatim-directive"></a>
78
+ #### The `@verbatim` Directive
79
+
80
+ 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:
81
+
82
+ ```rblade
83
+ @verbatim
84
+ <div class="container">
85
+ Hello, {{ name }}.
86
+ </div>
87
+ @endverbatim
88
+ ```
89
+
90
+ <a name="blade-directives"></a>
91
+ ## RBlade Directives
92
+
93
+ 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.
94
+
95
+ > [!NOTE]
96
+ > RBlade directives are case insensitive and ignore underscores, so depending on your preference, all of `@endif`, `@endIf` and `@end_if` are identical.
97
+
98
+ <a name="if-statements"></a>
99
+ ### If Statements
100
+
101
+ You may construct `if` statements using the `@if`, `@elseif`, `@else`, `@endif`, `@unless`, and `@endunless` directives. These directives function identically to their Ruby counterparts:
102
+
103
+ ```rblade
104
+ @unless(records.nil?)
105
+ @if (records.count === 1)
106
+ I have one record!
107
+ @elseif (records.count > 1)
108
+ I have multiple records!
109
+ @else
110
+ I don't have any records!
111
+ @endif
112
+ @endunless
113
+ ```
114
+
115
+ In addition to the conditional directives already discussed, the `@isset` and `@empty` directives may be used as convenient shortcuts for their respective PHP functions:
116
+ **TODO add nil? directive?**
117
+ ```rblade
118
+ @isset($records)
119
+ // $records is defined and is not null...
120
+ @endisset
121
+
122
+ @empty($records)
123
+ // $records is "empty"...
124
+ @endempty
125
+ ```
126
+
127
+ <a name="authentication-directives"></a>
128
+ #### Authentication Directives
129
+ **TODO add authentication directives?**
130
+ The `@auth` and `@guest` directives may be used to quickly determine if the current user is [authenticated](/docs/{{version}}/authentication) or is a guest:
131
+
132
+ ```rblade
133
+ @auth
134
+ // The user is authenticated...
135
+ @endauth
136
+
137
+ @guest
138
+ // The user is not authenticated...
139
+ @endguest
140
+ ```
141
+
142
+ If needed, you may specify the authentication guard that should be checked when using the `@auth` and `@guest` directives:
143
+
144
+ ```rblade
145
+ @auth('admin')
146
+ // The user is authenticated...
147
+ @endauth
148
+
149
+ @guest('admin')
150
+ // The user is not authenticated...
151
+ @endguest
152
+ ```
153
+
154
+ <a name="environment-directives"></a>
155
+ #### Environment Directives
156
+
157
+ You may check if the application is running in the production environment using the `@production` directive:
158
+
159
+ ```rblade
160
+ @production
161
+ // Production specific content...
162
+ @endproduction
163
+ ```
164
+
165
+ Or, you may determine if the application is running in a specific environment using the `@env` directive:
166
+
167
+ ```rblade
168
+ @env('staging')
169
+ // The application is running in "staging"...
170
+ @endenv
171
+
172
+ @env(['staging', 'production'])
173
+ // The application is running in "staging" or "production"...
174
+ @endenv
175
+ ```
176
+
177
+ <a name="session-directives"></a>
178
+ #### Session Directives
179
+ **TODO add sessuib directives**
180
+ 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:
181
+
182
+ ```rblade
183
+ @session('status')
184
+ <div class="p-4 bg-green-100">
185
+ {{ $value }}
186
+ </div>
187
+ @endsession
188
+ ```
189
+
190
+ <a name="switch-statements"></a>
191
+ ### Case Statements
192
+
193
+ Case statements can be constructed using the `@case`, `@when`, `@else` and `@endcase` directives:
194
+
195
+ ```rblade
196
+ @case(i)
197
+ @when(1)
198
+ First case...
199
+ @when(2)
200
+ Second case...
201
+ @else
202
+ Default case...
203
+ @endcase
204
+ ```
205
+
206
+ <a name="loops"></a>
207
+ ### Loops
208
+
209
+ In addition to conditional statements, RBlade provides simple directives for working with Ruby's loop structures:
210
+
211
+ ```rblade
212
+ @for (i in 0...10)
213
+ The current value is {{ i }}
214
+ @endfor
215
+
216
+ {{-- Compiles to users.each do |user| ... --}}
217
+ @each (user in users)
218
+ <p>This is user {{ user.id }}</p>
219
+ @endeach
220
+
221
+ @forelse (name in [])
222
+ <li>{{ name }}</li>
223
+ @empty
224
+ <p>No names</p>
225
+ @endforelse
226
+
227
+ @eachelse (user in users)
228
+ <li>{{ user.name }}</li>
229
+ @empty
230
+ <p>No users</p>
231
+ @endeachelse
232
+
233
+ @while (true)
234
+ <p>I'm looping forever.</p>
235
+ @endwhile
236
+ ```
237
+
238
+ When using loops you can also skip the current iteration or end the loop using the `@next` and `@break` directives:
239
+
240
+ ```rblade
241
+ for (user in users)
242
+ @if (user.type == 1)
243
+ @next
244
+ @endif
245
+
246
+ <li>{{ user.name }}</li>
247
+
248
+ @if (user.number == 5)
249
+ @break
250
+ @endif
251
+ @endfor
252
+ ```
253
+
254
+ You may also include the continuation or break condition within the directive declaration:
255
+
256
+ ```rblade
257
+ @foreach (user in users)
258
+ @next(user.type == 1)
259
+
260
+ <li>{{ $user->name }}</li>
261
+
262
+ @break(user.number == 5)
263
+ @endforeach
264
+ ```
265
+
266
+ <a name="the-loop-variable"></a>
267
+ ### The Loop Variable
268
+ **TODO can/should we add this?**
269
+ 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:
270
+
271
+ ```rblade
272
+ @foreach ($users as $user)
273
+ @if ($loop->first)
274
+ This is the first iteration.
275
+ @endif
276
+
277
+ @if ($loop->last)
278
+ This is the last iteration.
279
+ @endif
280
+
281
+ <p>This is user {{ $user->id }}</p>
282
+ @endforeach
283
+ ```
284
+
285
+ If you are in a nested loop, you may access the parent loop's `$loop` variable via the `parent` property:
286
+
287
+ ```rblade
288
+ @foreach ($users as $user)
289
+ @foreach ($user->posts as $post)
290
+ @if ($loop->parent->first)
291
+ This is the first iteration of the parent loop.
292
+ @endif
293
+ @endforeach
294
+ @endforeach
295
+ ```
296
+
297
+ The `$loop` variable also contains a variety of other useful properties:
298
+
299
+ <div class="overflow-auto">
300
+
301
+ | Property | Description |
302
+ | ------------------ | ------------------------------------------------------ |
303
+ | `$loop->index` | The index of the current loop iteration (starts at 0). |
304
+ | `$loop->iteration` | The current loop iteration (starts at 1). |
305
+ | `$loop->remaining` | The iterations remaining in the loop. |
306
+ | `$loop->count` | The total number of items in the array being iterated. |
307
+ | `$loop->first` | Whether this is the first iteration through the loop. |
308
+ | `$loop->last` | Whether this is the last iteration through the loop. |
309
+ | `$loop->even` | Whether this is an even iteration through the loop. |
310
+ | `$loop->odd` | Whether this is an odd iteration through the loop. |
311
+ | `$loop->depth` | The nesting level of the current loop. |
312
+ | `$loop->parent` | When in a nested loop, the parent's loop variable. |
313
+
314
+ </div>
315
+
316
+ <a name="conditional-classes"></a>
317
+ ### Conditional Classes & Styles
318
+
319
+ 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:
320
+
321
+ ```rblade
322
+ @ruby
323
+ isActive = false;
324
+ hasError = true;
325
+ @endruby
326
+
327
+ <span @class({
328
+ "p-4": true,
329
+ "font-bold": isActive,
330
+ "text-gray-500": !isActive,
331
+ "bg-red": hasError,
332
+ })></span>
333
+
334
+ <span class="p-4 text-gray-500 bg-red"></span>
335
+ ```
336
+
337
+ Likewise, the `@style` directive may be used to conditionally add inline CSS styles to an HTML element:
338
+
339
+ ```rblade
340
+ @ruby
341
+ isActive = true;
342
+ @endruby
343
+
344
+ <span @style({
345
+ "background-color: red": true,
346
+ "font-weight: bold" => isActive,
347
+ })></span>
348
+
349
+ <span style="background-color: red; font-weight: bold;"></span>
350
+ ```
351
+
352
+ <a name="additional-attributes"></a>
353
+ ### Additional Attributes
354
+
355
+ 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`:
356
+
357
+ ```rblade
358
+ <input type="checkbox"
359
+ name="active"
360
+ value="active"
361
+ @checked(user.active)) />
362
+ ```
363
+
364
+ Likewise, the `@selected` directive may be used to indicate if a given select option should be "selected":
365
+
366
+ ```rblade
367
+ <select name="version">
368
+ @each (version in product.versions)
369
+ <option value="{{ version }}" @selected(version == selectedVersion)>
370
+ {{ version }}
371
+ </option>
372
+ @endeach
373
+ </select>
374
+ ```
375
+
376
+ Additionally, the `@disabled` directive may be used to indicate if a given element should be "disabled":
377
+
378
+ ```rblade
379
+ <button type="submit" @disabled(isDisabled)>Submit</button>
380
+ ```
381
+
382
+ Moreover, the `@readonly` directive may be used to indicate if a given element should be "readonly":
383
+
384
+ ```rblade
385
+ <input type="email"
386
+ name="email"
387
+ value="email@laravel.com"
388
+ @readonly(!user.isAdmin) />
389
+ ```
390
+
391
+ In addition, the `@required` directive may be used to indicate if a given element should be "required":
392
+
393
+ ```rblade
394
+ <input type="text"
395
+ name="title"
396
+ value="title"
397
+ @required(user.isAdmin) />
398
+ ```
399
+
400
+ <a name="the-once-directive"></a>
401
+ ### The `@once` Directive
402
+
403
+ 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:
404
+
405
+ ```rblade
406
+ @once
407
+ @push('scripts')
408
+ <script>
409
+ // Your custom JavaScript...
410
+ </script>
411
+ @endPush
412
+ @endOnce
413
+ ```
414
+
415
+ 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:
416
+
417
+ ```rblade
418
+ @pushOnce('scripts')
419
+ <script>
420
+ {{-- Your javascript --}}
421
+ </script>
422
+ @endPushOnce
423
+ ```
424
+
425
+ 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:
426
+
427
+ ```rblade
428
+ @once(:heading)
429
+ <h1>Home page</h1>
430
+ @endOnce
431
+
432
+ {{-- This block will not be output --}}
433
+ @once(:heading)
434
+ <h1>Some other title</h1>
435
+ @endOnce
436
+ ```
437
+
438
+ > [!NOTE]
439
+ > The keys you use for `@once`, `@pushOnce` and `@prependOnce` are shared.
440
+
441
+ <a name="raw-ruby"></a>
442
+ ### Raw Ruby
443
+
444
+ 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:
445
+
446
+ ```rblade
447
+ @ruby
448
+ counter = 1;
449
+ @endruby
450
+ ```
451
+
452
+ **TODO add require?**
453
+ Or, if you only need to use PHP to import a class, you may use the `@use` directive:
454
+
455
+ ```rblade
456
+ @use('App\Models\Flight')
457
+ ```
458
+
459
+ A second argument may be provided to the `@use` directive to alias the imported class:
460
+
461
+ ```php
462
+ @use('App\Models\Flight', 'FlightModel')
463
+ ```
464
+
465
+ <a name="comments"></a>
466
+ ### Comments
467
+
468
+ 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.
469
+
470
+ ```rblade
471
+ {{-- This comment will not be present in the rendered HTML --}}
472
+ ```
473
+
474
+ <a name="components"></a>
475
+ ## Components
476
+
477
+ Components are a way of including sub-views into your templates. To illustrate how to use them, we will create a simple `alert` component.
478
+
479
+ 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.
480
+
481
+ Once your component has been created, it may be rendered using its tag alias:
482
+
483
+ ```rblade
484
+ <x-forms.alert/>
485
+ ```
486
+
487
+ <a name="rendering-components"></a>
488
+ ### Rendering Components
489
+
490
+ 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:
491
+
492
+ ```rblade
493
+ {{-- Render the `alert` component in app/views/components/ --}}
494
+ <x-alert/>
495
+
496
+ {{-- Render the `user-profile` component in app/views/components/ --}}
497
+ <x-user-profile/>
498
+ ```
499
+
500
+ 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:
501
+
502
+ ```rblade
503
+ {{-- Render the `text` component in app/views/components/form/inputs/ --}}
504
+ <x-form.inputs.text/>
505
+ ```
506
+
507
+ <a name="namespaces"></a>
508
+ #### Namespaces
509
+
510
+ 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.
511
+
512
+ Namespaced components can be rendered using the namespace as a prefix to the name separated by "::":
513
+
514
+ ```rblade
515
+ {{-- Render the `app` component in app/views/layouts/ --}}
516
+ <x-layout::app/>
517
+
518
+ {{-- Render the `home` component in app/views/ --}}
519
+ <x-view::home/>
520
+ ```
521
+
522
+ <a name="passing-data-to-components"></a>
523
+ ### Passing Data to Components
524
+
525
+ 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:
526
+
527
+ ```rblade
528
+ <x-alert type="error" :message="message"/>
529
+ ```
530
+
531
+ #### Component Properties
532
+
533
+ You can define a component's data properties using a `@props` statement at the top of the component. You can then reference these properties using local variables within the template:
534
+
535
+ ```rblade
536
+ {{-- alert.rblade --}}
537
+ @props({type: "warning", message: _required})
538
+ <div class="{{ type }}">{{ message }}</div>
539
+ ```
540
+
541
+ The `@props` statement 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:
542
+
543
+ ```rblade
544
+ {{-- This will give an error because the alert component requires a message propery --}}
545
+ <x-alert/>
546
+ ```
547
+
548
+ Kebab-case properties can be referenced using underscores in place of the dashes:
549
+
550
+ ```rblade
551
+ @props({"data-value": _required})
552
+ <div>{{ data_value }}</div>
553
+ ```
554
+
555
+ Properties that contain other non-alphanumeric characters or are Ruby reserved keywords are not created as local variables. However, you can reference them via the `attributes` local variable:
556
+
557
+ ```rblade
558
+ @props({"for": _required})
559
+ <div>{{ attributes[:for] }}</div>
560
+ ```
561
+
562
+ <a name="short-attribute-syntax"></a>
563
+ #### Short Attribute Syntax
564
+
565
+ 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:
566
+
567
+ ```rblade
568
+ {{-- Short attribute syntax... --}}
569
+ <x-profile :user_id :name />
570
+
571
+ {{-- Is equivalent to... --}}
572
+ <x-profile :user-id="user_id" :name="name" />
573
+ ```
574
+
575
+ <a name="escaping-attribute-rendering"></a>
576
+ #### Escaping Attribute Rendering
577
+
578
+ 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:
579
+
580
+ ```rblade
581
+ <x-button ::class="{ danger: isDeleting }">
582
+ Submit
583
+ </x-button>
584
+ ```
585
+
586
+ The following HTML will be rendered by RBlade:
587
+
588
+ ```rblade
589
+ <button :class="{ danger: isDeleting }">
590
+ Submit
591
+ </button>
592
+ ```
593
+
594
+ <a name="component-attributes"></a>
595
+ ### Component Attributes
596
+
597
+ 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:
598
+
599
+ ```rblade
600
+ <x-alert type="error" :message class="mt-4"/>
601
+ ```
602
+
603
+ **TODO remove from attributes bag using @props? Rename to attributes bag?**
604
+
605
+ 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:
606
+
607
+ ```rblade
608
+ <div {{ attributes }}>
609
+ <!-- Component content -->
610
+ </div>
611
+ ```
612
+
613
+ <a name="default-merged-attributes"></a>
614
+ #### Default / Merged Attributes
615
+
616
+ 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:
617
+
618
+ ```rblade
619
+ <div {{ attributes.merge({"class": "alert alert-#{type}"}) }}>
620
+ {{ message }}
621
+ </div>
622
+ ```
623
+
624
+ If we assume this component is utilized like so:
625
+
626
+ ```rblade
627
+ <x-alert type="error" :message class="mb-4"/>
628
+ ```
629
+
630
+ The final, rendered HTML of the component will appear like the following:
631
+
632
+ ```rblade
633
+ <div class="alert alert-error mb-4">
634
+ <!-- Contents of the message variable -->
635
+ </div>
636
+ ```
637
+
638
+ Both the `class` and `style` attributes are combined this way when using the `attributes.merge` method.
639
+
640
+ <a name="non-class-attribute-merging"></a>
641
+ #### Non-Class Attribute Merging
642
+
643
+ 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:
644
+
645
+ ```rblade
646
+ <button {{ attributes.merge({type: "button"}) }}>
647
+ {{ slot }}
648
+ </button>
649
+ ```
650
+
651
+ 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:
652
+
653
+ ```rblade
654
+ <x-button type="submit">
655
+ Submit
656
+ </x-button>
657
+ ```
658
+
659
+ The rendered HTML of the `button` component in this example would be:
660
+
661
+ ```rblade
662
+ <button type="submit">
663
+ Submit
664
+ </button>
665
+ ```
666
+
667
+ **Todo add prepends**
668
+ 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:
669
+
670
+ ```rblade
671
+ <div {{ attributes.merge({"data-controller": attributes.prepends("profile-controller")}) }}>
672
+ {{ slot }}
673
+ </div>
674
+ ```
675
+
676
+ <a name="conditionally-merge-classes"></a>
677
+ #### Conditionally Merge Classes
678
+ **TODO this**
679
+ 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:
680
+
681
+ ```rblade
682
+ <div {{ $attributes->class(['p-4', 'bg-red' => $hasError]) }}>
683
+ {{ $message }}
684
+ </div>
685
+ ```
686
+
687
+ If you need to merge other attributes onto your component, you can chain the `merge` method onto the `class` method:
688
+
689
+ ```rblade
690
+ <button {{ $attributes->class(['p-4'])->merge(['type' => 'button']) }}>
691
+ {{ $slot }}
692
+ </button>
693
+ ```
694
+
695
+ > [!NOTE]
696
+ > 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).
697
+
698
+ <a name="filtering-attributes"></a>
699
+ #### Retrieving and Filtering Attributes
700
+
701
+ **Todo this**
702
+
703
+ 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:
704
+
705
+ ```rblade
706
+ {{ $attributes->filter(fn (string $value, string $key) => $key == 'foo') }}
707
+ ```
708
+
709
+ For convenience, you may use the `whereStartsWith` method to retrieve all attributes whose keys begin with a given string:
710
+
711
+ ```rblade
712
+ {{ $attributes->whereStartsWith('wire:model') }}
713
+ ```
714
+
715
+ Conversely, the `whereDoesntStartWith` method may be used to exclude all attributes whose keys begin with a given string:
716
+
717
+ ```rblade
718
+ {{ $attributes->whereDoesntStartWith('wire:model') }}
719
+ ```
720
+
721
+ Using the `first` method, you may render the first attribute in a given attribute bag:
722
+
723
+ ```rblade
724
+ {{ $attributes->whereStartsWith('wire:model')->first() }}
725
+ ```
726
+
727
+ 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:
728
+
729
+ ```rblade
730
+ @if ($attributes->has('class'))
731
+ <div>Class attribute is present</div>
732
+ @endif
733
+ ```
734
+
735
+ If an array is passed to the `has` method, the method will determine if all of the given attributes are present on the component:
736
+
737
+ ```rblade
738
+ @if ($attributes->has(['name', 'class']))
739
+ <div>All of the attributes are present</div>
740
+ @endif
741
+ ```
742
+
743
+ The `hasAny` method may be used to determine if any of the given attributes are present on the component:
744
+
745
+ ```rblade
746
+ @if ($attributes->hasAny(['href', ':href', 'v-bind:href']))
747
+ <div>One of the attributes is present</div>
748
+ @endif
749
+ ```
750
+
751
+ You may retrieve a specific attribute's value using the `get` method:
752
+
753
+ ```rblade
754
+ {{ $attributes->get('class') }}
755
+ ```
756
+
757
+ <a name="slots"></a>
758
+ ### Slots
759
+
760
+ 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:
761
+
762
+ ```rblade
763
+ {{-- /app/views/components/alert.rblade --}}
764
+ <div class="alert alert-danger">
765
+ {{ slot }}
766
+ </div>
767
+ ```
768
+
769
+ We may pass content to the `slot` by injecting content into the component:
770
+
771
+ ```rblade
772
+ <x-alert>
773
+ <strong>Whoops!</strong> Something went wrong!
774
+ </x-alert>
775
+ ```
776
+
777
+ **TODO this**
778
+ 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:
779
+
780
+ ```rblade
781
+ {{-- /app/views/components/alert.rblade --}}
782
+ <span class="alert-title">{{ title }}</span>
783
+ <div class="alert alert-danger">
784
+ {{ slot }}
785
+ </div>
786
+ ```
787
+
788
+ 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:
789
+
790
+ ```xml
791
+ <x-alert>
792
+ <x-slot:title>
793
+ Server Error
794
+ </x-slot>
795
+
796
+ <strong>Whoops!</strong> Something went wrong!
797
+ </x-alert>
798
+ ```
799
+
800
+ You may invoke a slot's `isEmpty` method to determine if the slot contains content:
801
+
802
+ ```rblade
803
+ <span class="alert-title">{{ title }}</span>
804
+
805
+ <div class="alert alert-danger">
806
+ @if (slot.isEmpty)
807
+ This is default content if the slot is empty.
808
+ @else
809
+ {{ slot }}
810
+ @endif
811
+ </div>
812
+ ```
813
+
814
+ Additionally, the `hasActualContent` method may be used to determine if the slot contains any "actual" content that is not an HTML comment:
815
+
816
+ ```rblade
817
+ @if (slot.hasActualContent)
818
+ The scope has non-comment content.
819
+ @endif
820
+ ```
821
+
822
+ <a name="scoped-slots"></a>
823
+ #### Scoped Slots
824
+ **TODO can we do this easily?**
825
+ 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:
826
+
827
+ ```rblade
828
+ <x-alert>
829
+ <x-slot:title>
830
+ {{ $component->formatAlert('Server Error') }}
831
+ </x-slot>
832
+
833
+ <strong>Whoops!</strong> Something went wrong!
834
+ </x-alert>
835
+ ```
836
+
837
+ <a name="slot-attributes"></a>
838
+ #### Slot Attributes
839
+
840
+ Like RBlade components, you may assign additional [attributes](#component-attributes) to slots such as CSS class names:
841
+
842
+ ```xml
843
+ <x-card class="shadow-sm">
844
+ <x-slot:heading class="font-bold">
845
+ Heading
846
+ </x-slot>
847
+
848
+ Content
849
+
850
+ <x-slot:footer class="text-sm">
851
+ Footer
852
+ </x-slot>
853
+ </x-card>
854
+ ```
855
+
856
+ 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):
857
+
858
+ **TODO allow class to contain a string**
859
+ ```rblade
860
+ @props({
861
+ "heading": _required,
862
+ "footer": _required,
863
+ })
864
+
865
+ <div {{ attributes.class(['border']) }}>
866
+ <h1 {{ heading.attributes->class('text-lg': true) }}>
867
+ {{ heading }}
868
+ </h1>
869
+
870
+ {{ slot }}
871
+
872
+ <footer {{ footer.attributes.class('text-gray-700']) }}>
873
+ {{ footer }}
874
+ </footer>
875
+ </div>
876
+ ```
877
+
878
+ <a name="dynamic-components"></a>
879
+ ### Dynamic Components
880
+ **TODO add this**
881
+ 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:
882
+
883
+ ```rblade
884
+ @ruby(componentName = "secondary-button")
885
+ <x-dynamic-component :component="componentName" class="mt-4" />
886
+ ```
887
+
888
+ <a name="registering-additional-component-directories"></a>
889
+ ### Registering Additional Component Directories
890
+
891
+ 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:
892
+
893
+ ```ruby
894
+ require "rblade/component_store"
895
+
896
+ # Auto-discover components in the app/components directory
897
+ RBlade::ComponentStore.add_path(Rails.root.join("app", "components"))
898
+
899
+ # Auto-discover components in the app/views/partials directory with the namespace "partial"
900
+ RBlade::ComponentStore.add_path(Rails.root.join("app", "views", "partials"), "partial")
901
+ ```
902
+
903
+ If multiple directories are registered with the same namespace, RBlade will search for components in all the directories in the order they were registered.
904
+
905
+ <a name="manually-registering-components"></a>
906
+ ### Manually Registering Components
907
+ **TODO would this be useful? It'd be useful for testing...**
908
+ > [!WARNING]
909
+ > 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.
910
+
911
+ When writing components for your own application, components are automatically discovered within the `app/View/Components` directory and `resources/views/components` directory.
912
+
913
+ 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:
914
+
915
+ use Illuminate\Support\Facades\Blade;
916
+ use VendorPackage\View\Components\AlertComponent;
917
+
918
+ /**
919
+ * Bootstrap your package's services.
920
+ */
921
+ public function boot(): void
922
+ {
923
+ Blade::component('package-alert', AlertComponent::class);
924
+ }
925
+
926
+ Once your component has been registered, it may be rendered using its tag alias:
927
+
928
+ ```rblade
929
+ <x-package-alert/>
930
+ ```
931
+
932
+ <a name="anonymous-index-components"></a>
933
+ ### Index Components
934
+
935
+ 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:
936
+
937
+ ```rblade
938
+ <x-accordion>
939
+ <x-accordion.item>
940
+ ...
941
+ </x-accordion.item>
942
+ </x-accordion>
943
+ ```
944
+
945
+ You could make these components with files in separate directories:
946
+
947
+ ```none
948
+ /app/views/components/accordion.rblade
949
+ /app/views/components/accordion/item.rblade
950
+ ```
951
+
952
+ 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:
953
+
954
+ ```none
955
+ /app/views/components/accordion/index.rblade
956
+ /app/views/components/accordion/item.rblade
957
+ ```
958
+
959
+ <a name="accessing-parent-data"></a>
960
+ ### Accessing Parent Data
961
+ **TODO this? It might be complicated**
962
+ 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>`:
963
+
964
+ ```rblade
965
+ <x-menu color="purple">
966
+ <x-menu.item>...</x-menu.item>
967
+ <x-menu.item>...</x-menu.item>
968
+ </x-menu>
969
+ ```
970
+
971
+ The `<x-menu>` component may have an implementation like the following:
972
+
973
+ ```rblade
974
+ <!-- /resources/views/components/menu/index.rblade -->
975
+
976
+ @props(['color' => 'gray'])
977
+
978
+ <ul {{ $attributes->merge(['class' => 'bg-'.$color.'-200']) }}>
979
+ {{ $slot }}
980
+ </ul>
981
+ ```
982
+
983
+ 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:
984
+
985
+ ```rblade
986
+ <!-- /resources/views/components/menu/item.rblade -->
987
+
988
+ @aware(['color' => 'gray'])
989
+
990
+ <li {{ $attributes->merge(['class' => 'text-'.$color.'-800']) }}>
991
+ {{ $slot }}
992
+ </li>
993
+ ```
994
+
995
+ > [!WARNING]
996
+ > 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.
997
+
998
+ <a name="forms"></a>
999
+ ## Forms
1000
+
1001
+ <a name="csrf-field"></a>
1002
+ ### CSRF Field
1003
+ **TODO I don't think we need this?**
1004
+ 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:
1005
+
1006
+ ```rblade
1007
+ <form method="POST" action="/profile">
1008
+ @csrf
1009
+
1010
+ ...
1011
+ </form>
1012
+ ```
1013
+
1014
+ <a name="method-field"></a>
1015
+ ### Method Field
1016
+ **TODO add this**
1017
+ 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:
1018
+
1019
+ ```rblade
1020
+ <form action="/foo/bar" method="POST">
1021
+ @method('PUT')
1022
+
1023
+ ...
1024
+ </form>
1025
+ ```
1026
+
1027
+ <a name="validation-errors"></a>
1028
+ ### Validation Errors
1029
+ **TODO this**
1030
+ 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:
1031
+
1032
+ ```rblade
1033
+ <!-- /resources/views/post/create.rblade -->
1034
+
1035
+ <label for="title">Post Title</label>
1036
+
1037
+ <input id="title"
1038
+ type="text"
1039
+ class="@error('title') is-invalid @enderror">
1040
+
1041
+ @error('title')
1042
+ <div class="alert alert-danger">{{ $message }}</div>
1043
+ @enderror
1044
+ ```
1045
+
1046
+ 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:
1047
+
1048
+ ```rblade
1049
+ <!-- /resources/views/auth.rblade -->
1050
+
1051
+ <label for="email">Email address</label>
1052
+
1053
+ <input id="email"
1054
+ type="email"
1055
+ class="@error('email') is-invalid @else is-valid @enderror">
1056
+ ```
1057
+
1058
+ 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:
1059
+
1060
+ ```rblade
1061
+ <!-- /resources/views/auth.rblade -->
1062
+
1063
+ <label for="email">Email address</label>
1064
+
1065
+ <input id="email"
1066
+ type="email"
1067
+ class="@error('email', 'login') is-invalid @enderror">
1068
+
1069
+ @error('email', 'login')
1070
+ <div class="alert alert-danger">{{ $message }}</div>
1071
+ @enderror
1072
+ ```
1073
+
1074
+ <a name="stacks"></a>
1075
+ ## Stacks
1076
+
1077
+ 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:
1078
+
1079
+ ```rblade
1080
+ @push('scripts')
1081
+ <script src="/example.js"></script>
1082
+ @endpush
1083
+ ```
1084
+
1085
+ If you would like to `@push` content if a given boolean expression evaluates to `true`, you may use the `@pushIf` directive:
1086
+ **TODO add this**
1087
+ ```rblade
1088
+ @pushIf(shouldPush, 'scripts')
1089
+ <script src="/example.js"></script>
1090
+ @endPushIf
1091
+ ```
1092
+
1093
+ 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:
1094
+
1095
+ ```rblade
1096
+ <head>
1097
+ <!-- Head Contents -->
1098
+
1099
+ @stack('scripts')
1100
+ </head>
1101
+ ```
1102
+
1103
+ If you would like to prepend content onto the beginning of a stack, you should use the `@prepend` directive:
1104
+
1105
+ ```rblade
1106
+ @push('scripts')
1107
+ This will be second...
1108
+ @endpush
1109
+
1110
+ // Later...
1111
+
1112
+ @prepend('scripts')
1113
+ This will be first...
1114
+ @endprepend
1115
+ ```
1116
+
1117
+ <a name="rendering-blade-fragments"></a>
1118
+ ## Rendering Blade Fragments
1119
+ **TODO this?**
1120
+ 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:
1121
+
1122
+ ```rblade
1123
+ @fragment('user-list')
1124
+ <ul>
1125
+ @foreach ($users as $user)
1126
+ <li>{{ $user->name }}</li>
1127
+ @endforeach
1128
+ </ul>
1129
+ @endfragment
1130
+ ```
1131
+
1132
+ 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:
1133
+
1134
+ ```php
1135
+ return view('dashboard', ['users' => $users])->fragment('user-list');
1136
+ ```
1137
+
1138
+ 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:
1139
+
1140
+ ```php
1141
+ return view('dashboard', ['users' => $users])
1142
+ ->fragmentIf($request->hasHeader('HX-Request'), 'user-list');
1143
+ ```
1144
+
1145
+ The `fragments` and `fragmentsIf` methods allow you to return multiple view fragments in the response. The fragments will be concatenated together:
1146
+
1147
+ ```php
1148
+ view('dashboard', ['users' => $users])
1149
+ ->fragments(['user-list', 'comment-list']);
1150
+
1151
+ view('dashboard', ['users' => $users])
1152
+ ->fragmentsIf(
1153
+ $request->hasHeader('HX-Request'),
1154
+ ['user-list', 'comment-list']
1155
+ );
1156
+ ```
1157
+
1158
+ <a name="extending-blade"></a>
1159
+ ## Extending Blade
1160
+ **TODO this?**
1161
+ 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.
1162
+
1163
+ The following example creates a `@datetime($var)` directive which formats a given `$var`, which should be an instance of `DateTime`:
1164
+
1165
+ <?php
1166
+
1167
+ namespace App\Providers;
1168
+
1169
+ use Illuminate\Support\Facades\Blade;
1170
+ use Illuminate\Support\ServiceProvider;
1171
+
1172
+ class AppServiceProvider extends ServiceProvider
1173
+ {
1174
+ /**
1175
+ * Register any application services.
1176
+ */
1177
+ public function register(): void
1178
+ {
1179
+ // ...
1180
+ }
1181
+
1182
+ /**
1183
+ * Bootstrap any application services.
1184
+ */
1185
+ public function boot(): void
1186
+ {
1187
+ Blade::directive('datetime', function (string $expression) {
1188
+ return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
1189
+ });
1190
+ }
1191
+ }
1192
+
1193
+ 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:
1194
+
1195
+ <?php echo ($var)->format('m/d/Y H:i'); ?>
1196
+
1197
+ > [!WARNING]
1198
+ > 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.
1199
+
1200
+ <a name="custom-echo-handlers"></a>
1201
+ ### Custom Echo Handlers
1202
+ **TODO this? Need to do something similar for attribute manager anyway**
1203
+ 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.
1204
+
1205
+ 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:
1206
+
1207
+ use Illuminate\Support\Facades\Blade;
1208
+ use Money\Money;
1209
+
1210
+ /**
1211
+ * Bootstrap any application services.
1212
+ */
1213
+ public function boot(): void
1214
+ {
1215
+ Blade::stringable(function (Money $money) {
1216
+ return $money->formatTo('en_GB');
1217
+ });
1218
+ }
1219
+
1220
+ Once your custom echo handler has been defined, you may simply echo the object in your Blade template:
1221
+
1222
+ ```rblade
1223
+ Cost: {{ $money }}
1224
+ ```
1225
+
1226
+ <a name="custom-if-statements"></a>
1227
+ ### Custom If Statements
1228
+ **TODO this**
1229
+ 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`:
1230
+
1231
+ use Illuminate\Support\Facades\Blade;
1232
+
1233
+ /**
1234
+ * Bootstrap any application services.
1235
+ */
1236
+ public function boot(): void
1237
+ {
1238
+ Blade::if('disk', function (string $value) {
1239
+ return config('filesystems.default') === $value;
1240
+ });
1241
+ }
1242
+
1243
+ Once the custom conditional has been defined, you can use it within your templates:
1244
+
1245
+ ```rblade
1246
+ @disk('local')
1247
+ <!-- The application is using the local disk... -->
1248
+ @elsedisk('s3')
1249
+ <!-- The application is using the s3 disk... -->
1250
+ @else
1251
+ <!-- The application is using some other disk... -->
1252
+ @enddisk
1253
+
1254
+ @unlessdisk('local')
1255
+ <!-- The application is not using the local disk... -->
1256
+ @enddisk
1257
+ ```