Laravel slot variable name has the same name as another variable

Viewed 346

I am passing

<x-slot name="customLayout"> custom content goes here </x-slot>

So In Laravel blade I can print it using:

{{ $customLayout }}

BUT, in component blade I have another variable which has the same variable name of $customLayout and it's a String.

I don't want to change variable name, because I get it through associative array keys and I want it to be the same as slot name so I can know where custom slot is going to be printed.

When I do {{ $customLayout }} in component I get String printed and not the passed template from <x-slot name="customLayout">.

Is there a way to print slots passed content instead of local variable?

1 Answers

In PHP, variable scope is either global (outside of all functions) or local (inside a function, for example). Template languages have their own way of how they pass the parameters you have to the template. The behavior you have detected indicates that the environment you use is scoping the variables globally, which is not surprising. As a result you do not have two variables with the same name, but a single variable where you intend to store two values, but instead of that, the first value is overwritten by the second.

Storing two different values in a single variable is impossible. This means that you need an alternative. You could create a class for component properties/attributes either with static fields or instantiating it, maybe as a singleton. And then, instead of using $customLayout which overrides your template parameter value, you could use something like $attributes->customLayout. If you dislike this approach, then you can use a prefix for your variable.

EDIT

According to the comment of Marco, the variable variable of $$customLayout did the trick, because, it turned out that the String variable contained the actual name of the variable to be displayed.

Related