At the moment I can successfully display some generated content in my blade view by calling a variable with a key, like this:
<div> {{ $data['key'] }} </div>
What I would like to achieve, is to reuse the key for a class name for example. The reason for that is that I want to easily access this content with JavaScript by using a selector. Something that would look like this:
<div class='key'> {{ $data['key'] }} </div>
This code work, but as I have many fields, I would like to avoid duplicating the key. To achieve that, I thought of creating a blade components, and pass the key in the slot. So that I can reuse this key both in the class name, and in the placeholder for data.
But it seems that my variable {{ $data }}
is not accessible from my component file, as it throws the error: $data is undefined
.
Here is my code:
<!-- In main.blade.php --> @component('my-component') key @endcomponent
<!-- In my-component.blade.php --> <div class="{{ $slot }}"> {{ $data[$slot] }} </div>
I am not familiar to Blade so I am open to another approach if necessary.
Advertisement
Answer
You should pass your data and key as arguments to your component, thereby being more explicit. You don’t need to use a slot for this, as a slot is generally used for blocks of text or HTML, not for simple attributes.
Create your component like this,
<div class="{{ $key }}"> {{ $data[$key] }} </div>
And then render it like this
@component('my-component', ['data' => $data, 'key' => 'key'])