Basil Gass
Basil Gass

Reputation: 352

AlpineJS inline function and Laravel @json

I have a problem passing a PHP variable to a variable inside an alpine variable or function. Here is a simple example.

@php
$test = "Hello World's testing";
@endphp

<div x-data="{
    message: @json($test)
}">

<span x-text="message"></span>
</div>

The problem comes from the fact that x-data is using the double-quote to wrap the encoded data. I know I could "externalize" the x-data, but I really need it to be inline.

I have a basic workaround (using backticks) for example, but I wanted to know if there is a better way to do this.

EDIT The example is using a string... but the PHP variable can be a boolean or even an array. That's why I'm using @json.

Upvotes: 2

Views: 3090

Answers (2)

Jeff N
Jeff N

Reputation: 146

Will this not work?:

@php
$test = "Hello World's testing";
@endphp

<div x-data="{
    message: {{ json_encode($test) }}
}">

<span x-text="message"></span>
</div>

Upvotes: 1

NICO
NICO

Reputation: 1843

I' d use Template Strings.. Easy to read, no need to escape multiple quotes.

<div>
    @php
    $test = "Hello World's testing";
    @endphp

    <div x-data="{
        message: `{{ $test }}`
    }">
        <span x-text="message"></span>
    </div>

</div>

Upvotes: 2

Related Questions