Laravel Blade directive adding extra quotes

Viewed 354

Im using Laravel 7 so I didnt think this was going to be an issue.

Just a note on my installation, it was an upgrade from 5.3.

My issue is with a custom Blade directive I created. It is aded additional quotes around the input

I added a dd() to see why my Helper didnt work.

My ServiceProvider

    Blade::directive('setting', function ($expression) {
        dd($expression);
        return SettingHelper::value($expression);
    });

View file

@setting('theme_public')

Output of dd()

"'theme_public'"

Expected output

'theme_public'

I dont know why the extra quotes are being added.

1 Answers

You are right, I get the same behavior with a fresh laravel 7 installation.

I created some little tests, to see what's going on. I think the behavior is best explained like this. Imagine you are calling a view with one variable:

return view('welcome', ['var' => "Hallo"]);

You have a custom blade directive like this:

Blade::directive('dirtest', function ($expression) {
    dd($expression);
});

If you use that in your template the output is this:

@dirtest($var)
// output of dd in the browser:
"$var"

So it seems like the blade directives are just meant to replace some shorthand directive with more verbose php code. The actual code get's executed later in the blade templating engine. That makes sense, since blade templates are also cached for faster execution. In the cached version that custom directive is already embedded and your custom function doesn't get fired anymore. I hope that explanation makes sense to you.

What that means for you

It really depends on your use case. If you have a custom directive, that only gets passed constant strings, you could probably get away with just writing:

@setting(theme_public)

But if there's just a slight chance, that you might pass in a variable from time to time, like

@setting($theme)

You really have to return code, that utilizes that variable and can be evaluated later.

Related