PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] Default values for Laravel 5.4+ blades new components?

 February 20, 2022     laravel, laravel-5, laravel-5.4, php     No comments   

Issue

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.


Solution

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.



Answered By - Jessedc
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing