1

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( {{ $var1 }}, {{ $var2 }}) @test( {!! $var1 !!}, {!! $var2 !!}) @test( {{{ $var1 }}}, {{{ $var2 }}}) 

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.*.

1
  • Change the return to return "<?php echo $arg1 . ' ' . $arg2; ?>"; Commented Sep 27, 2017 at 11:42

2 Answers 2

4

Edit: Finally I have the real solution.

You need to add the line starts with list to return statement because blade creates a php file in storage/framework/views directory after replacing directives. So you need something like the followings.

Blade::directive('test', function($expression){ return '<?php list($arg1, $arg2) = explode(\',\',str_replace([\'(\',\')\',\' \'], \'\', ' . $expression . ')); echo "$arg1 -- $arg2"; ?>'; }); 

Finally you can use it like followings;

@php($expression = "(0,1)") @test($expression) @test("(10,12)") //It works now 

Note: you should create BladeServiceProvider in Providers directory then you should add it to providers in config/app.php. Then you can add your directive to BladeServiceProvider. It is not important. It is just more proper way than yours.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this, after you have done making your custom blade:

php artisan view:clear.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.