Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values for Laravel 5.4+ blades new components?

Laravel 5.4+ allows for components of the following structure:

<div class="alert alert-{{ $type }}">
    <div class="alert-title">{{ $title }}</div>
    {{ $slot }}
</div>

Which are called like:

@component('alert', ['type' => 'danger'])
    @slot('title') 
        oh no 
    @endslot
    Foo
@endcomponent

Is there a shorthand or blade marker to set default values for the variables passed in?

For example, in the above, if I don't pass in "type" I get a undefined variable error. I could do something like:

<div class="alert alert-{{ isset($type) ? $type : 'default' }}">

But the above feels verbose, especially if the variable is used in multiple spots.

like image 241
Chris Avatar asked Mar 23 '17 03:03

Chris


People also ask

What is blade component in Laravel?

Blade components are a subset of blade template that allow you to create new custom, reusable, encapsulated PHP and HTML. For example you may want to create a navbar to be used in many of your application pages. So you build your navbar as a component and can reused the component wherever you want.

What is yield (' content ') in Laravel?

In Laravel, @yield is principally used to define a section in a layout and is constantly used to get content from a child page unto a master page.

What is Laravel blade template?

The Blade is a powerful templating engine in a Laravel framework. The blade allows to use the templating engine easily, and it makes the syntax writing very simple. The blade templating engine provides its own structure such as conditional statements and loops.


1 Answers

I don't think it does.

Having said that blade has the or operator that wraps the isset() call (see docs).

<div class="alert alert-{{ $type or 'default' }}">

If you're running php 7 this is a case for the Null coalescing operator.

<div class="alert alert-{{ $type ?? 'default' }}">

Both will make your call site tider.

like image 72
Jessedc Avatar answered Sep 21 '22 09:09

Jessedc