JSON Templates
Return JSON responses from Kirby templates instead of HTML.
JSON Templates
When writing a Kirby template, it will be rendered as HTML by default. To opt-in to JSON templates, you can encode the template data as JSON and return it as a response. This is useful for headless setups where KQL is not sufficient or you want to control the data structure in PHP.
Kirby Headless does not interfere with Kirby's default routing. To overwrite Kirby's global routing to return JSON templates, set the globalRoutes
option in your config.php
:
config.php
return [
'headless' => [
'globalRoutes' => true
]
];
Template Example
Writing templates as JSON is straightforward. Here is an example of how to encode the data of an about
template as JSON:
site/templates/about.php
$data = [
'title' => $page->title()->value(),
'layout' => $page->layout()->toLayouts()->toArray(),
'address' => $page->address()->value(),
'email' => $page->email()->value(),
'phone' => $page->phone()->value(),
'social' => $page->social()->toStructure()->toArray()
];
echo \Kirby\Data\Json::encode($data);
To fetch the JSON template data, you can use the following JavaScript example:
const response = await fetch("https://example.com/about", {
headers: {
Authorization: `Bearer ${process.env.KIRBY_API_TOKEN}`,
},
});
const data = await response.json();
console.log(data);