Check if variable exist in laravel's blade directive

♀尐吖头ヾ 提交于 2021-01-20 16:16:06

问题


I'm trying to create blade directive which echo variable (if variable defined) or echo "no data" if variable undefined.

This is my code in AppServiceProvider.php:

<?php

namespace App\Providers;

use Blade;
use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('p', function($ex) {
            error_log(print_r($ex,true));
            return '<?php $defined_vars = get_defined_vars(); if(array_key_exists(\''. $ex .'\', $defined_vars) ): echo ' . $ex . ' ; else: echo \'no data\'; endif;?>';
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Here is my index.blade.php:

<p class="lead">@p($myvar)</p>

But my directive "p" gives "no data" if variable defined. If I use isset error occurres: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

How could I check inside directives if variable defined?


回答1:


Blade has a directive to check if a variable is set:

@isset($var)

@endisset



回答2:


For Laravel 5.7 onwards use.

{{ $checkvariable ?? 'not-exist' }}




回答3:


You can use in Blade functionality for checking isset i.e

{{ $checkvariable or 'not-exist' }}

https://laravel.com/docs/5.2/blade#displaying-data




回答4:


Try checking if the variable is empty:

@if(empty($myvar))
    <p>Data does not exist</p>
@else
    <p>Your data is here!</p>
@endif

Can also check this thread




回答5:


The best and cleanest way check if a variable exists in blade:

 {!! !empty($myvariable) ? $myvariable : 'variable does not exist' !!}



回答6:


For Laravel version >=5.7

{{ $value ?? '' }}

For Laravel version <5.7

{{ $value or '' }}



回答7:


You can use the @isset blade directive to check whether the variable is set or not. Alternatively, if you have the default value for that variable you can directly use it as {{ $vatiable ?? 'default_value' }}. The ?? way is available in Laravel v5.7 onwards.

If you want to check for multiple variables at once, you can do it by applying AND operation to expression as @if(isset($var_one) && isset($var_two)).

There are also other ways (lengthy) using @if directive as @if(isset($variable)) but it's not recommended.

Some developer uses @ symbol for error control in a similar situation. The at-sign (@) is used as error control operator in PHP. When an expression is prepended with the @ sign, error messages that might be generated by that expression will be ignored. If the track_errors feature is enabled, an error message generated by the expression and it will be saved in the variable $php_errormsg. This variable will be overwritten on each error. The use of @ is very bad programming practice as it does not make the error disappear, it just hides them, and it makes debugging a lot worse since we can’t see what’s actually wrong with our code.




回答8:


What are you trying to pass to your custom directive? If it's just a string/int the following should work.

Blade::directive('p', function($expression){
    $output = $expression ? $expression : 'nodata';
    return "<?php echo {$output}; ?>";
});

In Blade Template

@p('Foo')



回答9:


The @empty directive might be useful:

@empty($var)
   $var is unset or false-y
@endempty



回答10:


You can do it in few different ways.

Sample-1:

@if( !empty($data['var']))
   {{ $data['var'] }} 
@endif

Sample-2:

{{ $data['var'] or 'no data found' }}

Sample-3: Using ternary operator

<a href="" class="{{ ( ! empty($data['var'] ? $data['var'] : 'no data found') }}">



回答11:


If you trying check a bool variable you can use @unless

<input type="text" class="@unless ($variable) d-none @endunless" >




回答12:


For the last version of Larvael make the variable optional in the blade template. Replace $myvar with {{ $myvar }} with {{ $myvar?? '' }}




回答13:


To check if variable exist in Laravel blade directive, do this:

Blade::directive('datetime', function ($value) {
    
    return "<?php echo isset($value) ? ($value)->format('d/m/Y H:i:s') : null; ?>";
    
});


来源:https://stackoverflow.com/questions/37425978/check-if-variable-exist-in-laravels-blade-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!