Passing data to React frontend #7570
-
Hi, I'm trying to get my data passed from the antlers template to my React app - ideally in a way where I can enable SSR. This isn't so difficult with something like <script>
// I created my own modifier because {{ page | to_json | entities }} refuses to hydrate content fully
// (Why? Why does Statamic constantly give me empty arrays where data should be?)
const pageData = JSON.parse(`<?php echo '{{ page | jsonify }}'; ?>`.replace(/[\n\t]/g, ''));
// Access pageData when rendering component...
</script> What's seemingly impossible is getting navigation trees to the template in JSON format. I decided the best thing to do is create my own ViewModel and do something like the following: <?php
namespace App\ViewModels;
use Statamic\View\ViewModel;
use Statamic\Facades\Nav;
class ReactModel extends ViewModel
{
public function data(): array
{
$footer = Nav::findByHandle("footer");
// $footer->trees is an empty array!
return [
'footerNav' => collect($footer->trees)
];
}
} But the I'm not a PHP developer, so I'm likely going about this the wrong way. Could someone explain to me how to properly send the required data, in JSON format, to my template? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I've solved the problem by implementing my own Facade like so: <?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
use Statamic\Contracts\Structures\NavTreeRepository;
class NavTree extends Facade
{
protected static function getFacadeAccessor()
{
return NavTreeRepository::class;
}
} NavTreeRepository has a |
Beta Was this translation helpful? Give feedback.
-
trees() should be called as a method:
|
Beta Was this translation helpful? Give feedback.
I've solved the problem by implementing my own Facade like so:
NavTreeRepository has a
find
method, which gives me the data I need.