livewire / volt

Volt is an elegantly crafted functional API for Livewire.
https://livewire.laravel.com/docs/volt
MIT License
327 stars 19 forks source link

php blocks don't work as expected in anonymous volt components #57

Closed inmanturbo closed 11 months ago

inmanturbo commented 11 months ago

Volt Version

1.3.2

Laravel Version

10.24.0

PHP Version

8.2.10

Database Driver & Version

N/A

Description

Undefined variable for variable declared within @php block

Steps To Reproduce

<?php

use function Livewire\Volt\{state};

state(['count' => 0]);

?>

<div>
@volt('mycomponent')
    <div>
    @php
        $number = 3;
    @endphp
    <div>
        {{ $number }}
    </div>
    </div>
@endvolt
ErrorException
PHP 8.2.10
10.24.0
Undefined variable $number

    <div>

    |---LINE:13---|@__raw_block_0__@

    <div>

        |---LINE:17---|{{ $number }}

    </div>

    </div>

|---LINE:20---|

Demo repo: https://github.com/inmanturbo/volt-bug-report

ADDITIONAL INFO (EDIT): If you avoid the error by not attempting to use the variable, you will see @__raw_block_0__@ in your browser.

Example use case:

@foreach($this->posts as $post)
    @php
       if($post->getThirdPartyService()?->getResource() && $loop->index % 2 == 0) {
           // set styles etc
           $myComponentClass = 'bg-indigo-100';

       }elseif($post->getThirdPartyService()?->getResource()){

           $myComponentClass = 'bg-green-100';

       }elseif( .. other conditions ...){

           // etc
       }
    @endphp

     <x-my-component :class='$myComponentClass' />
....
@endforeach