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?
Assumption #1: You Know The Variable Exists Within The View. REMEMBER: an empty array will always return false. Therefore, there is no real need to run it through a function like empty or is null. Comparing it to null will tell you if it exists or not.
A blade encapsulates all the required resources – JavaScript, HTML, CSS, XML, images, etc – to implement a particular high level feature. For example, a blade might implement a map UI, a chat window, a charting module or an alerting mechanism.
Blade has a directive to check if a variable is set:
@isset($var) @endisset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With