mercredi 27 septembre 2017

Blade Custom Directive receives value as a string instead of its original value

I'm newbie in Laravel, researched but i can't find a solution for something so simple. I created a custom directive namely "test" for Blade in the app/Providers/AppServiceProvider.php file:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    /**
    * Bootstrap any application services.
    *
    * @return void
    */
    public function boot()
    {
        Blade::directive('test', function($expression){
            // Dumps as well: "$var1 , $var2"
            dump($expression);

            list($arg1, $arg2) = explode(',',str_replace(['(',')',' '], '', $expression));

            // will print: $var1 , $var2
            return "<?php echo '$arg1 , $arg2'; ?>";
        }); 
    }

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

Theoretically, its usage should be very simple inside a blade template, however as shown in the following example the directive is printing the literal value of the arguments e.g $var1 is printing $var1 instead of its real content "test a":

<?php 
    $var1 = 'test a'; 
    $var2 = 'test b'; 
?>

// Prints: $var1 , $var2
// Expected: "test a test b"
@test($var1 , $var2)

Already tried to print their values using multiple tags:

@test( , )
@test( {!! $var1 !!}, {!! $var2 !!})
@test( }, })

But doesn't work neither, the directive is always receiving the name of the variable instead of its content. What am I ignoring in this case? Any help is appreciated. I am using Laravel 5.4.*.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire