检查laravel的Blade指令中是否存在变量

问题描述:

我正在尝试创建叶片指令,如果变量未定义,该指令将回显变量(如果已定义变量)或回显无数据".

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

这是我在 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()
    {
        //
    }
}

这是我的index.blade.php:

Here is my index.blade.php:

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

但是,如果定义了变量,我的指令"p"将给出无数据".如果我使用isset错误,则会发生:不能在表达式的结果上使用isset()(您可以改用"null!== expression")

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?

刀片有指令来检查是否设置了变量:

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

@isset($var)

@endisset