Home > Software design >  How to pass a string to a blade component?
How to pass a string to a blade component?

Time:09-16

As an example there is this component:

resources/views/components/example.blade.php

<div>
    @if($foo === "bar")
        Bar
    @else
        Foo
    @endif
</div>

that I render like

@php
   $foo = "bar";
@endphp
<x-example :foo="$foo" />

what is working. But to have my code looking cleaner, I want to pass the string directly to the component, but the following I tried are not working:

<x-example :foo="bar" />
<x-example :foo='bar' />
<x-example :foo="\'bar\'" />
<x-example :foo="'bar'" />
<x-example :foo=""bar"" />

CodePudding user response:

Easy mistake to make, as mentioned in the Laravel documentation on passing data to components;

You may pass data to Blade components using HTML attributes. Hard-coded, primitive values may be passed to the component using simple HTML attribute strings. PHP expressions and variables should be passed to the component via attributes that use the : character as a prefix

So update how you use the Blade component as below:

<x-example foo="bar" />
  • Related