jonassiewertsen / statamic-livewire

A Laravel Livewire integration for Statamics antlers engine
85 stars 15 forks source link

Global Statamic Variables #9

Closed valschr closed 3 years ago

valschr commented 3 years ago

Using global Statamic variables with Antlers would be very useful, but since livewire is not persisting private variables through render cycles and setting the global set to a public variable on mount will produce an error I'm not quite sure what the best practice for this would be.

This approach works, but doesn't feel right to me:

public function mount($fallbacks) {
        session(['fallbacks' => $fallbacks]);
}

public function render()
{
    return view('blocks.counter', [
      "fallbacks" => session('fallbacks'),
    ]);
}

An this is how the component is getting called:

{{ livewire:counter :fallbacks="fallbacks" }}

Would be awesome do add some best practice to the readme.

Thanks,

jonassiewertsen commented 3 years ago

Private Livewire variables will never persist through render cycles, which is expected and wanted behavior.

I am not sure what your fallback variable does contain, but the following might be an option:

public $fallbacks;

public function mount() 
{
    $this->fallback =  session('fallbacks');
}

public function render()
{
    return view('blocks.counter');
}

No need to pass it into the mount variable, if fetching directly from a session. If you do use a public attribute, you don't need to pass it directly into the view method, this will happen automatically.

More information on Livewire Properties: https://laravel-livewire.com/docs/2.x/properties#initializing-properties