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 AppProviders;
use Blade;
use IlluminateSupportServiceProvider;
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?
question from:
https://stackoverflow.com/questions/37425978/check-if-variable-exist-in-laravels-blade-directive 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…