Blade Templates PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides an introduction to Blade templates, a templating engine in the Laravel PHP framework. It covers basic usage, including displaying data, handling HTML entity encoding, and using dynamic features.
Full Transcript
Blade Templates Introduction Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates. In fact, all Blade templates are compiled into plain PHP code and cached until...
Blade Templates Introduction Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates. In fact, all Blade templates are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade template files use the.blade.php file extension and are typically stored in the resources/views directory. Blade views may be returned from routes or controllers using the global view helper. Of course, as mentioned in the documentation on views, data may be passed to the Blade view using the view helper's second argument: Route::get('/', function () { return view('greeting', \['name' =\> 'Finn'\]); }); Supercharging Blade With Livewire Want to take your Blade templates to the next level and build dynamic interfaces with ease? Check out Laravel Livewire. Livewire allows you to write Blade components that are augmented with dynamic functionality that would typically only be possible via frontend frameworks like React or Vue, providing a great approach to building modern, reactive frontends without the complexities, client-side rendering, or build steps of many JavaScript frameworks. Displaying Data You may display data that is passed to your Blade views by wrapping the variable in curly braces. For example, given the following route: Route::get('/', function () { return view('welcome', \['name' =\> 'Samantha'\]); }); You may display the contents of the name variable like so: Hello, {{ \$name }}. Blade's {{ }} echo statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. You are not limited to displaying the contents of the variables passed to the view. You may also echo the results of any PHP function. In fact, you can put any PHP code you wish inside of a Blade echo statement: The current UNIX timestamp is {{ time() }}. HTML Entity Encoding By default, Blade (and the Laravel e function) will double encode HTML entities. If you would like to disable double encoding, call the Blade::withoutDoubleEncoding method from the boot method of your AppServiceProvider: Laravel Hello, @{{ name }}. In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to be rendered by your JavaScript framework. The @ symbol may also be used to escape Blade directives: {{-- Blade template --}} @[\@if]{.citation data-cites="if"}() [\@if]{.citation data-cites="if"}() Rendering JSON Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example: However, instead of manually calling json\_encode, you may use the Illuminate::from method directive. The from method accepts the same arguments as PHP's json\_encode function; however, it will ensure that the resulting JSON is properly escaped for inclusion within HTML quotes. The from method will return a string JSON.parse JavaScript statement that will convert the given object or array into a valid JavaScript object: The latest versions of the Laravel application skeleton include a Js facade, which provides convenient access to this functionality within your Blade templates: You should only use the Js::from method to render existing variables as JSON. The Blade templating is based on regular expressions and attempts to pass a complex expression to the directive may cause unexpected failures. The [\@verbatim]{.citation data-cites="verbatim"} Directive If you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the [\@verbatim]{.citation data-cites="verbatim"} directive so that you do not have to prefix each Blade echo statement with an @ symbol: [\@verbatim]{.citation data-cites="verbatim"} ::: {.container} Hello, {{ name }}. [\@endverbatim]{.citation data-cites="endverbatim"} Blade Directives In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP 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 PHP counterparts. If Statements You may construct if statements using the [\@if]{.citation data-cites="if"}, [\@elseif]{.citation data-cites="elseif"}, [\@else]{.citation data-cites="else"}, and [\@endif]{.citation data-cites="endif"} directives. These directives function identically to their PHP counterparts: [\@if]{.citation data-cites="if"} (count([*records*) = = = 1)*Ihaveonerecord*!@*elseif*(*count*(]{.math.inline}records) \> 1) I have multiple records! [\@else]{.citation data-cites="else"} I don't have any records! [\@endif]{.citation data-cites="endif"} For convenience, Blade also provides an [\@unless]{.citation data-cites="unless"} directive: [\@unless]{.citation data-cites="unless"} (Auth::check()) You are not signed in. [\@endunless]{.citation data-cites="endunless"} In addition to the conditional directives already discussed, the [\@isset]{.citation data-cites="isset"} and [\@empty]{.citation data-cites="empty"} directives may be used as convenient shortcuts for their respective PHP functions: [\@isset]{.citation data-cites="isset"}(\$records) // \$records is defined and is not null... [\@endisset]{.citation data-cites="endisset"} [\@empty]{.citation data-cites="empty"}(\$records) // \$records is "empty"... [\@endempty]{.citation data-cites="endempty"} Authentication Directives The [\@auth]{.citation data-cites="auth"} and [\@guest]{.citation data-cites="guest"} directives may be used to quickly determine if the current user is authenticated or is a guest: [\@auth]{.citation data-cites="auth"} // The user is authenticated... [\@endauth]{.citation data-cites="endauth"} [\@guest]{.citation data-cites="guest"} // The user is not authenticated... [\@endguest]{.citation data-cites="endguest"} If needed, you may specify the authentication guard that should be checked when using the [\@auth]{.citation data-cites="auth"} and [\@guest]{.citation data-cites="guest"} directives: [\@auth]{.citation data-cites="auth"}('admin') // The user is authenticated... [\@endauth]{.citation data-cites="endauth"} [\@guest]{.citation data-cites="guest"}('admin') // The user is not authenticated... [\@endguest]{.citation data-cites="endguest"} Environment Directives You may check if the application is running in the production environment using the [\@production]{.citation data-cites="production"} directive: [\@production]{.citation data-cites="production"} // Production specific content... [\@endproduction]{.citation data-cites="endproduction"} Or, you may determine if the application is running in a specific environment using the [\@env]{.citation data-cites="env"} directive: [\@env]{.citation data-cites="env"}('staging') // The application is running in "staging"... [\@endenv]{.citation data-cites="endenv"} [\@env]{.citation data-cites="env"}(\['staging', 'production'\]) // The application is running in "staging" or "production"... [\@endenv]{.citation data-cites="endenv"} Section Directives You may determine if a template inheritance section has content using the [\@hasSection]{.citation data-cites="hasSection"} directive: [\@hasSection]{.citation data-cites="hasSection"}('navigation') ::: {.pull-right} @yield('navigation') [\@endif]{.citation data-cites="endif"} You may use the sectionMissing directive to determine if a section does not have content: [\@sectionMissing]{.citation data-cites="sectionMissing"}('navigation') ::: {.pull-right} @include('default-navigation') [\@endif]{.citation data-cites="endif"} Session Directives The [\@session]{.citation data-cites="session"} directive may be used to determine if a session value exists. If the session value exists, the template contents within the [\@session]{.citation data-cites="session"} and [\@endsession]{.citation data-cites="endsession"} directives will be evaluated. Within the [\@session]{.citation data-cites="session"} directive's contents, you may echo the \$value variable to display the session value: [\@session]{.citation data-cites="session"}('status') ::: {.p-4.bg-green-100} {{ $value }} [\@endsession]{.citation data-cites="endsession"} Switch Statements Switch statements can be constructed using the [\@switch]{.citation data-cites="switch"}, [\@case]{.citation data-cites="case"}, [\@break]{.citation data-cites="break"}, [\@default]{.citation data-cites="default"} and [\@endswitch]{.citation data-cites="endswitch"} directives: [\@switch]{.citation data-cites="switch"}(\$i) [\@case]{.citation data-cites="case"}(1) First case... [\@break]{.citation data-cites="break"} @case(2) Second case... @break @default Default case... [\@endswitch]{.citation data-cites="endswitch"} Loops In addition to conditional statements, Blade provides simple directives for working with PHP's loop structures. Again, each of these directives functions identically to their PHP counterparts: [\@for]{.citation data-cites="for"} (\$i = 0; \$i \< 10; \$i++) The current value is {{ \$i }} [\@endfor]{.citation data-cites="endfor"} [\@foreach]{.citation data-cites="foreach"} (\$users as \$user) This is user {{ \$user-\>id }} [\@endforeach]{.citation data-cites="endforeach"} [\@forelse]{.citation data-cites="forelse"} (\$users as \$user) {{ \$user-\>name }} [\@empty]{.citation data-cites="empty"} No users [\@endforelse]{.citation data-cites="endforelse"} [\@while]{.citation data-cites="while"} (true) I'm looping forever. [\@endwhile]{.citation data-cites="endwhile"} While iterating through a foreach loop, you may use the loop variable to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop. When using loops you may also skip the current iteration or end the loop using the [\@continue]{.citation data-cites="continue"} and [\@break]{.citation data-cites="break"} directives: [\@foreach]{.citation data-cites="foreach"} (\$users as [*user*)@*if*(]{.math.inline}user-\>type == 1) [\@continue]{.citation data-cites="continue"} [\@endif]{.citation data-cites="endif"} {{ $user->name }} @if ($user->number == 5) @break @endif [\@endforeach]{.citation data-cites="endforeach"} You may also include the continuation or break condition within the directive declaration: [\@foreach]{.citation data-cites="foreach"} (\$users as [*user*)@*continue*(]{.math.inline}user-\>type == 1) {{ $user->name }} @break($user->number == 5) [\@endforeach]{.citation data-cites="endforeach"} The Loop Variable While iterating through a foreach loop, a \$loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop: [\@foreach]{.citation data-cites="foreach"} (\$users as [*user*)@*if*(]{.math.inline}loop-\>first) This is the first iteration. [\@endif]{.citation data-cites="endif"} @if ($loop->last) This is the last iteration. @endif This is user {{ $user->id }} [\@endforeach]{.citation data-cites="endforeach"} If you are in a nested loop, you may access the parent loop's \$loop variable via the parent property: [\@foreach]{.citation data-cites="foreach"} (\$users as [*user*)@*foreach*(]{.math.inline}user-\>posts as [*post*)@*if*(]{.math.inline}loop-\>parent-\>first) This is the first iteration of the parent loop. [\@endif]{.citation data-cites="endif"} [\@endforeach]{.citation data-cites="endforeach"} [\@endforeach]{.citation data-cites="endforeach"} The \$loop variable also contains a variety of other useful properties: Property Description \$loop-\>index The index of the current loop iteration (starts at 0). \$loop-\>iteration The current loop iteration (starts at 1). \$loop-\>remaining The iterations remaining in the loop. \$loop-\>count The total number of items in the array being iterated. \$loop-\>first Whether this is the first iteration through the loop. \$loop-\>last Whether this is the last iteration through the loop. \$loop-\>even Whether this is an even iteration through the loop. \$loop-\>odd Whether this is an odd iteration through the loop. \$loop-\>depth The nesting level of the current loop. \$loop-\>parent When in a nested loop, the parent's loop variable. Conditional Classes & Styles The [\@class]{.citation data-cites="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: [\@php]{.citation data-cites="php"} \$isActive = false; \$hasError = true; [\@endphp]{.citation data-cites="endphp"} \ \$isActive, 'text-gray-500' =\> ! \$isActive, 'bg-red' =\> \$hasError,\])\> []{.p-4.text-gray-500.bg-red} Likewise, the [\@style]{.citation data-cites="style"} directive may be used to conditionally add inline CSS styles to an HTML element: [\@php]{.citation data-cites="php"} \$isActive = true; [\@endphp]{.citation data-cites="endphp"} \ \$isActive,\])\> []{style="background-color: red; font-weight: bold;"} Additional Attributes For convenience, you may use the [\@checked]{.citation data-cites="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: \active)) /\> Likewise, the [\@selected]{.citation data-cites="selected"} directive may be used to indicate if a given select option should be "selected": [\@foreach]{.citation data-cites="foreach"} (\$product-\>versions as \$version) \ {{ \$version }} [\@endforeach]{.citation data-cites="endforeach"} Additionally, the [\@disabled]{.citation data-cites="disabled"} directive may be used to indicate if a given element should be "disabled": \isNotEmpty())\>Submit Moreover, the [\@readonly]{.citation data-cites="readonly"} directive may be used to indicate if a given element should be "readonly": \isNotAdmin()) /\> In addition, the [\@required]{.citation data-cites="required"} directive may be used to indicate if a given element should be "required": \isAdmin()) /\> Including Subviews While you're free to use the [\@include]{.citation data-cites="include"} directive, Blade components provide similar functionality and offer several benefits over the [\@include]{.citation data-cites="include"} directive such as data and attribute binding. Blade's [\@include]{.citation data-cites="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: @include('shared.errors') 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: [\@include]{.citation data-cites="include"}('view.name', \['status' =\> 'complete'\]) If you attempt to [\@include]{.citation data-cites="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]{.citation data-cites="includeIf"} directive: [\@includeIf]{.citation data-cites="includeIf"}('view.name', \['status' =\> 'complete'\]) If you would like to [\@include]{.citation data-cites="include"} a view if a given boolean expression evaluates to true or false, you may use the [\@includeWhen]{.citation data-cites="includeWhen"} and [\@includeUnless]{.citation data-cites="includeUnless"} directives: [\@includeWhen]{.citation data-cites="includeWhen"}(\$boolean, 'view.name', \['status' =\> 'complete'\]) [\@includeUnless]{.citation data-cites="includeUnless"}(\$boolean, 'view.name', \['status' =\> 'complete'\]) To include the first view that exists from a given array of views, you may use the includeFirst directive: [\@includeFirst]{.citation data-cites="includeFirst"}(\['custom.admin', 'admin'\], \['status' =\> 'complete'\]) 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. Rendering Views for Collections You may combine loops and includes into one line with Blade's [\@each]{.citation data-cites="each"} directive: [\@each]{.citation data-cites="each"}('view.name', \$jobs, 'job') The [\@each]{.citation data-cites="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. You may also pass a fourth argument to the [\@each]{.citation data-cites="each"} directive. This argument determines the view that will be rendered if the given array is empty. [\@each]{.citation data-cites="each"}('view.name', \$jobs, 'job', 'view.empty') Views rendered via [\@each]{.citation data-cites="each"} do not inherit the variables from the parent view. If the child view requires these variables, you should use the [\@foreach]{.citation data-cites="foreach"} and [\@include]{.citation data-cites="include"} directives instead. The [\@once]{.citation data-cites="once"} Directive The [\@once]{.citation data-cites="once"} directive allows you to define a portion of the template that will only be evaluated once per rendering cycle. This may be useful for pushing a given piece of JavaScript into the page's header using stacks. For example, if you are rendering a given component within a loop, you may wish to only push the JavaScript to the header the first time the component is rendered: [\@once]{.citation data-cites="once"} [\@push]{.citation data-cites="push"}('scripts') @endpush [\@endonce]{.citation data-cites="endonce"} Since the [\@once]{.citation data-cites="once"} directive is often used in conjunction with the [\@push]{.citation data-cites="push"} or [\@prepend]{.citation data-cites="prepend"} directives, the [\@pushOnce]{.citation data-cites="pushOnce"} and [\@prependOnce]{.citation data-cites="prependOnce"} directives are available for your convenience: [\@pushOnce]{.citation data-cites="pushOnce"}('scripts') [\@endPushOnce]{.citation data-cites="endPushOnce"} Raw PHP In some situations, it's useful to embed PHP code into your views. You can use the Blade [\@php]{.citation data-cites="php"} directive to execute a block of plain PHP within your template: [\@php]{.citation data-cites="php"} \$counter = 1; [\@endphp]{.citation data-cites="endphp"} Or, if you only need to use PHP to import a class, you may use the [\@use]{.citation data-cites="use"} directive: [\@use]{.citation data-cites="use"}('App') A second argument may be provided to the [\@use]{.citation data-cites="use"} directive to alias the imported class: [\@use]{.citation data-cites="use"}('App', 'FlightModel') Comments 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: {{-- This comment will not be present in the rendered HTML --}} Components 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. 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: php artisan make:component Alert 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. You may also create components within subdirectories: php artisan make:component Forms/Input 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. 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: php artisan make:component forms.input --view The command above will create a Blade file at resources/views/components/forms/input.blade.php which can be rendered as a component via \. Manually Registering Package Components When writing components for your own application, components are automatically discovered within the app/View/Components directory and resources/views/components directory. However, if you are building a package that utilizes Blade components, 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: use Illuminate; /\*\* \* Bootstrap your package's services. \*/ public function boot(): void { Blade::component('package-alert', Alert::class); } Once your component has been registered, it may be rendered using its tag alias: 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 Packagenamespace: use Illuminate; /\*\* \* Bootstrap your package's services. \*/ public function boot(): void { Blade::componentNamespace('Nightshade\\Views\\Components', 'nightshade'); } This will allow the usage of package components by their vendor namespace using the package-name:: syntax: \ \ 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. Rendering Components To display a component, you may use a Blade component tag within one of your Blade templates. Blade component tags start with the string x- followed by the kebab case name of the component class: 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: \ 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: use Illuminate; /\*\* \* Whether the component should be rendered \*/ public function shouldRender(): bool { return Str::length(\$this-\>message) \> 0; } Index Components Sometimes components are part of a component group and you may wish to group the related components within a single directory. For example, imagine a "card" component with the following class structure: App App App Since the root Card component is nested within a Card directory, you might expect that you would need to render the component via \. However, when a component's file name matches the name of the component's directory, Laravel automatically assumes that component is the "root" component and allows you to render the component without repeating the directory name: \...\ \...\ Passing Data to Components 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: \ 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: {{ \$message }} ::: Casing 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: /\*\* \* Create the component instance. \*/ public function \_\_construct( public string \$alertType, ) {} The \$alertType argument may be provided to the component like so: Short Attribute Syntax When passing attributes to components, you may also use a "short attribute" syntax. This is often convenient since attribute names frequently match the variable names they correspond to: {{-- Short attribute syntax... --}} \ {{-- Is equivalent to... --}} \ Escaping Attribute Rendering Since some JavaScript frameworks such as Alpine.js also use colon-prefixed attributes, you may use a double colon (::) prefix to inform Blade that the attribute is not a PHP expression. For example, given the following component: \ Submit The following HTML will be rendered by Blade: \ Submit Component Methods 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: /\*\* \* Determine if the given option is the currently selected option. \*/ public function isSelected(string \$option): bool { return \$option === \$this-\>selected; } You may execute this method from your component template by invoking the variable matching the name of the method: \ {{ \$label }} Accessing Attributes and Slots Within Component Classes 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: use Closure; /\*\* \* Get the view / contents that represent the component. \*/ public function render(): Closure { return function () { return '\Components content ::: '; }; } The closure returned by your component's render method may also receive a \$data array as its only argument. This array will contain several elements that provide information about the component: return function (array \$data) { // \$data\['componentName'\]; // \$data\['attributes'\]; // \$data\['slot'\]; return '\Components content ::: '; } The elements in the \$data array should never be directly embedded into the Blade string returned by your render method, as doing so could allow remote code execution via malicious attribute content. The componentName is equal to the name used in the HTML tag after the x- prefix. So '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 Illuminateinstance with the contents of the component's slot. 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. Additional Dependencies If your component requires dependencies from Laravel's service container, you may list them before any of the component's data attributes and they will automatically be injected by the container: use App; /\*\* \* Create the component instance. \*/ public function \_\_construct( public AlertCreator \$creator, public string \$type, public string \$message, ) {} Hiding Attributes / Methods 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: 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: Using directives such as [\@env]{.citation data-cites="env"} within component tags is not supported at this time. For example, \ will not be compiled. Default / Merged Attributes Sometimes you may need to specify default values for attributes or merge additional values into some of the component's attributes. To accomplish this, you may use the attribute 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: merge(\[\'class\' =\> \'alert alert-\'.\$type\]) }}\> {{ \$message }} If we assume this component is utilized like so: \ The final, rendered HTML of the component will appear like the following: ::: {.alert.alert-error.mb-4} ::: Conditionally Merge Classes 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: class(\[\'p-4\', \'bg-red\' =\> \$hasError\]) }}\> {{ \$message }} If you need to merge other attributes onto your component, you can chain the merge method onto the class method: \class(\['p-4'\])-\>merge(\['type' =\> 'button'\]) }}\> {{ \$slot }} If you need to conditionally compile classes on other HTML elements that shouldn't receive merged attributes, you can use the [\@class]{.citation data-cites="class"} directive. Non-Class Attribute Merging 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: \merge(\['type' =\> 'button'\]) }}\> {{ \$slot }} 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: Submit The rendered HTML of the button component in this example would be: Submit 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: merge(\[\'data-controller\' =\> \$attributes-\>prepends(\'profile-controller\')\]) }}\> {{ \$slot }} Retrieving and Filtering Attributes You may filter attributes using the filter method. This method accepts a closure which should return true if you wish to retain the attribute in the attribute bag: {{ \$attributes-\>filter(fn (string \$value, string \$key) =\> \$key == 'foo') }} For convenience, you may use the whereStartsWith method to retrieve all attributes whose keys begin with a given string: {{ \$attributes-\>whereStartsWith('wire:model') }} Conversely, the whereDoesntStartWith method may be used to exclude all attributes whose keys begin with a given string: {{ \$attributes-\>whereDoesntStartWith('wire:model') }} Using the first method, you may render the first attribute in a given attribute bag: {{ \$attributes-\>whereStartsWith('wire:model')-\>first() }} If you would like to check if an attribute is present on the component, you may use the has method. This method accepts the attribute name as its only argument and returns a boolean indicating whether or not the attribute is present: [\@if]{.citation data-cites="if"} (\$attributes-\>has('class')) Class attribute is present [\@endif]{.citation data-cites="endif"} If an array is passed to the has method, the method will determine if all of the given attributes are present on the component: [\@if]{.citation data-cites="if"} (\$attributes-\>has(\['name', 'class'\])) All of the attributes are present [\@endif]{.citation data-cites="endif"} The hasAny method may be used to determine if any of the given attributes are present on the component: [\@if]{.citation data-cites="if"} (\$attributes-\>hasAny(\['href', ':href', 'v-bind:href'\])) One of the attributes is present [\@endif]{.citation data-cites="endif"} You may retrieve a specific attribute's value using the get method: {{ \$attributes-\>get('class') }} Reserved Keywords 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: data render resolveView shouldRender view withAttributes withName Slots 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: ::: {.alert.alert-danger} {{ $slot }} ::: We may pass content to the slot by injecting content into the component: **Whoops!** Something went wrong! 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: [{{ \$title }}]{.alert-title} ::: {.alert.alert-danger} {{ $slot }} ::: 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: Server Error Whoops! Something went wrong! You may invoke a slot's isEmpty method to determine if the slot contains content: [{{ \$title }}]{.alert-title} ::: {.alert.alert-danger} @if ($slot->isEmpty()) This is default content if the slot is empty. @else {{ $slot }} @endif ::: Additionally, the hasActualContent method may be used to determine if the slot contains any "actual" content that is not an HTML comment: [\@if]{.citation data-cites="if"} (\$slot-\>hasActualContent()) The scope has non-comment content. [\@endif]{.citation data-cites="endif"} Scoped Slots 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: {{ \$component-\>formatAlert('Server Error') }} Whoops! Something went wrong! Slot Attributes Like Blade components, you may assign additional attributes to slots such as CSS class names: Heading Content Footer 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: [\@props]{.citation data-cites="props"}(\[ 'heading', 'footer',\]) class(\[\'border\'\]) }}\> attributes-\>class(\[\'text-lg\'\]) }}\> {{ \$heading }} ======================================================== {{ \$slot }} attributes-\>class(\[\'text-gray-700\'\]) }}\> {{ \$footer }} Inline Component Views 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: /\*\* \* Get the view / contents that represent the component. \*/ public function render(): string { return \ 'info', 'message'\]) merge(\[\'class\' =\> \'alert alert-\'.\$type\]) }}\> {{ \$message }} Given the component definition above, we may render the component like so: \ Accessing Parent Data Sometimes you may want to access data from a parent component inside a child component. In these cases, you may use the [\@aware]{.citation data-cites="aware"} directive. For example, imagine we are building a complex menu component consisting of a parent and child \: \...\ \...\ The component may have an implementation like the following: [\@props]{.citation data-cites="props"}(\['color' =\> 'gray'\]) Because the color prop was only passed into the parent (), it won't be available inside \. However, if we use the [\@aware]{.citation data-cites="aware"} directive, we can make it available inside \ as well: [\@aware]{.citation data-cites="aware"}(\['color' =\> 'gray'\]) merge(\[\'class\' =\> \'text-\'.\$color.\'-800\'\]) }}\> {{ \$slot }} The [\@aware]{.citation data-cites="aware"} directive cannot access parent data that is not explicitly passed to the parent component via HTML attributes. Default [\@props]{.citation data-cites="props"} values that are not explicitly passed to the parent component cannot be accessed by the [\@aware]{.citation data-cites="aware"} directive. Anonymous Component Paths 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. 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: /\*\* \* Bootstrap any application services. \*/ public function boot(): void { Blade::anonymousComponentPath(**DIR**.'/../components'); } 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: Prefix "namespaces" may be provided as the second argument to the anonymousComponentPath method: Blade::anonymousComponentPath(**DIR**.'/../components', 'dashboard'); 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: \ Building Layouts Layouts Using Components 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 and then use it throughout our application. Defining the Layout Component For example, imagine we are building a "todo" list application. We might define a layout component that looks like the following: {{ \$title ?? 'Todo Manager' }} Todos ===== ------------------------------------------------------------------------ {{ \$slot }} Applying the Layout Component 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: [\@foreach]{.citation data-cites="foreach"} (\$tasks as \$task) {{ \$task }} [\@endforeach]{.citation data-cites="endforeach"} 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: Custom Title [\@foreach]{.citation data-cites="foreach"} (\$tasks as \$task) {{ \$task }} [\@endforeach]{.citation data-cites="endforeach"} Now that we have defined our layout and task list views, we just need to return the task view from a route: use App; Route::get('/tasks', function () { return view('tasks', \['tasks' =\> Task::all()\]); }); Layouts Using Template Inheritance Defining a Layout Layouts may also be created via "template inheritance". This was the primary way of building applications prior to the introduction of components. 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: App Name - [\@yield]{.citation data-cites="yield"}('title') [\@section]{.citation data-cites="section"}('sidebar') This is the master sidebar. [\@show]{.citation data-cites="show"} ::: {.container} @yield('content') As you can see, this file contains typical HTML mark-up. However, take note of the [\@section]{.citation data-cites="section"} and [\@yield]{.citation data-cites="yield"} directives. The [\@section]{.citation data-cites="section"} directive, as the name implies, defines a section of content, while the [\@yield]{.citation data-cites="yield"} directive is used to display the contents of a given section. Now that we have defined a layout for our application, let's define a child page that inherits the layout. Extending a Layout When defining a child view, use the [\@extends]{.citation data-cites="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]{.citation data-cites="section"} directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using [\@yield]{.citation data-cites="yield"}: [\@extends]{.citation data-cites="extends"}('layouts.app') [\@section]{.citation data-cites="section"}('title', 'Page Title') [\@section]{.citation data-cites="section"}('sidebar') [\@parent]{.citation data-cites="parent"} This is appended to the master sidebar. [\@endsection]{.citation data-cites="endsection"} [\@section]{.citation data-cites="section"}('content') This is my body content. [\@endsection]{.citation data-cites="endsection"} In this example, the sidebar section is utilizing the [\@parent]{.citation data-cites="parent"} directive to append (rather than overwriting) content to the layout's sidebar. The [\@parent]{.citation data-cites="parent"} directive will be replaced by the content of the layout when the view is rendered. Contrary to the previous example, this sidebar section ends with [\@endsection]{.citation data-cites="endsection"} instead of [\@show]{.citation data-cites="show"}. The [\@endsection]{.citation data-cites="endsection"} directive will only define a section while [\@show]{.citation data-cites="show"} will define and immediately yield the section. The [\@yield]{.citation data-cites="yield"} directive also accepts a default value as its second parameter. This value will be rendered if the section being yielded is undefined: [\@yield]{.citation data-cites="yield"}('content', 'Default content') Forms CSRF Field Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the [\@csrf]{.citation data-cites="csrf"} Blade directive to generate the token field: [\@csrf]{.citation data-cites="csrf"}... Method Field 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]{.citation data-cites="method"} Blade directive can create this field for you: [\@method]{.citation data-cites="method"}('PUT')... Validation Errors The [\@error]{.citation data-cites="error"} directive may be used to quickly check if validation error messages exist for a given attribute. Within an [\@error]{.citation data-cites="error"} directive, you may echo the \$message variable to display the error message: Post Title [\@error]{.citation data-cites="error"}('title') ::: {.alert.alert-danger} {{ \$message }} ::: [\@enderror]{.citation data-cites="enderror"} Since the [\@error]{.citation data-cites="error"} directive compiles to an "if" statement, you may use the [\@else]{.citation data-cites="else"} directive to render content when there is not an error for an attribute: Email address You may pass the name of a specific error bag as the second parameter to the [\@error]{.citation data-cites="error"} directive to retrieve validation error messages on pages containing multiple forms: Email address [\@error]{.citation data-cites="error"}('email', 'login') ::: {.alert.alert-danger} {{ \$message }} ::: [\@enderror]{.citation data-cites="enderror"} Stacks 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: [\@push]{.citation data-cites="push"}('scripts') [\@endpush]{.citation data-cites="endpush"} If you would like to [\@push]{.citation data-cites="push"} content if a given boolean expression evaluates to true, you may use the [\@pushIf]{.citation data-cites="pushIf"} directive: [\@pushIf]{.citation data-cites="pushIf"}(\$shouldPush, 'scripts') [\@endPushIf]{.citation data-cites="endPushIf"} You may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the [\@stack]{.citation data-cites="stack"} directive: [\@stack]{.citation data-cites="stack"}('scripts') If you would like to prepend content onto the beginning of a stack, you should use the [\@prepend]{.citation data-cites="prepend"} directive: [\@push]{.citation data-cites="push"}('scripts') This will be second... [\@endpush]{.citation data-cites="endpush"} // Later... [\@prepend]{.citation data-cites="prepend"}('scripts') This will be first... [\@endprepend]{.citation data-cites="endprepend"} Service Injection The [\@inject]{.citation data-cites="inject"} directive may be used to retrieve a service from the Laravel service container. The first argument passed to [\@inject]{.citation data-cites="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: [\@inject]{.citation data-cites="inject"}('metrics', 'App') Monthly Revenue: {{ $metrics->monthlyRevenue() }}. Rendering Inline Blade Templates 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: use Illuminate; return Blade::render('Hello, {{ \$name }}', \['name' =\> 'Julian Bashir'\]); 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: return Blade::render( 'Hello, {{ \$name }}', \['name' =\> 'Julian Bashir'\], deleteCachedView: true ); Rendering Blade Fragments When using frontend frameworks such as Turbo and htmx, you may occasionally need to only return a portion of a Blade template within your HTTP response. Blade "fragments" allow you to do just that. To get started, place a portion of your Blade template within [\@fragment]{.citation data-cites="fragment"} and [\@endfragment]{.citation data-cites="endfragment"} directives: [\@fragment]{.citation data-cites="fragment"}('user-list') - {{ \$user-\>name }} [\@endfragment]{.citation data-cites="endfragment"} Then, when rendering the view that utilizes this template, you may invoke the fragment method to specify that only the specified fragment should be included in the outgoing HTTP response: return view('dashboard', \['users' =\> \$users\])-\>fragment('user-list'); The fragmentIf method allows you to conditionally return a fragment of a view based on a given condition. Otherwise, the entire view will be returned: return view('dashboard', \['users' =\> \$users\]) -\>fragmentIf(\$request-\>hasHeader('HX-Request'), 'user-list'); The fragments and fragmentsIf methods allow you to return multiple view fragments in the response. The fragments will be concatenated together: view('dashboard', \['users' =\> \$users\]) -\>fragments(\['user-list', 'comment-list'\]); view('dashboard', \['users' =\> \$users\]) -\>fragmentsIf( \$request-\>hasHeader('HX-Request'), \['user-list', 'comment-list'\] ); Extending Blade Blade allows you to define your own custom directives using the directive method. When the Blade compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains. The following example creates a [\@datetime]{.citation data-cites="datetime"}(\$var) directive which formats a given \$var, which should be an instance of DateTime: format('m/d/Y H:i'); ?\> 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. Custom Echo Handlers If you attempt to "echo" an object using Blade, the object's \_\_toString method will be invoked. The \_\_toString method is one of PHP's built-in "magic methods". However, sometimes you may not have control over the \_\_toString method of a given class, such as when the class that you are interacting with belongs to a third-party library. In these cases, Blade allows you to register a custom echo handler for that particular type of object. To accomplish this, you should invoke Blade's stringable method. The stringable method accepts a closure. This closure should type-hint the type of object that it is responsible for rendering. Typically, the stringable method should be invoked within the boot method of your application's AppServiceProvider class: use Illuminate; use Money; /\*\* \* Bootstrap any application services. \*/ public function boot(): void { Blade::stringable(function (Money \$money) { return \$money-\>formatTo('en\_GB'); }); } Once your custom echo handler has been defined, you may simply echo the object in your Blade template: Cost: {{ \$money }} Custom If Statements Programming a custom directive is sometimes more complex than necessary when defining simple, custom conditional statements. For that reason, Blade provides a Blade::if method which allows you to quickly define custom conditional directives using closures. For example, let's define a custom conditional that checks the configured default "disk" for the application. We may do this in the boot method of our AppServiceProvider: use Illuminate; /\*\* \* Bootstrap any application services. \*/ public function boot(): void { Blade::if('disk', function (string \$value) { return config('filesystems.default') === \$value; }); } Once the custom conditional has been defined, you can use it within your templates: [\@disk]{.citation data-cites="disk"}('local') [\@elsedisk]{.citation data-cites="elsedisk"}('s3') [\@else]{.citation data-cites="else"} [\@enddisk]{.citation data-cites="enddisk"} [\@unlessdisk]{.citation data-cites="unlessdisk"}('local') [\@enddisk]{.citation data-cites="enddisk"} ::: ::: :::