I mostly do it as follows:
- Create a page method, e.g.
$page->json()that returns an array of information about some page:
/* your Kirby plugin */
'pageMethods' => [
'json' => function (): array {
return [
'title' => $this->title()->value(),
'path' => $this->id(),
'template' => $this->intendedTemplate()->name(),
/* or any other fields that you need */
];
}
]
2a. You can already call that $page->json() to get that array. For example if you want to use that in some JS on your frontend:
<!-- snippet/header.php -->
<script>
let pageData = <?= json_encode( $page->json() ) ?>;
console.log( pageData );
</script>
2b. But maybe you want to fetch that json with JS at a later stage. For that, create a /json/... route that returns your array:
'routes' => [
[
'pattern' => 'json/(:all)',
'method' => 'GET',
'action' => function ( $id ) {
return page( $id )->json();
}
]
]
You can now fetch site.com/json/page-id to get your page data.
- Going from here:
- Use page models to adjust the result of
$page->json()to a specific content type/template - Implement some cache inside that route
- Add also
$pages->json(),$file->json(),$files->json(),$site->json()
Code not tested, may be stupid, just to demonstrate a possible approach
I am working on a plugin as a boilerplate for that. You can find the current state here, but this is far from it’s final stage: GitHub - moritzebeling/kirby-headless: Public and customizable Json API Endpoint for Kirby CMS