Content Representations allow you to output the content in different formats. Be it JSON for your frontend JS library of choice or to use Kirby as an API for other tools, an automatic RSS feed representation of your blog or a plain text representation of your résumé.
In this example, we will create a JSON representation of the
default template. After we are done, all pages with the
default template will also be available in JSON. We will see below how exactly that works.
A representation is defined by its representation template. For our JSON representation, let's create a file
default.json.php in our
/site/templates directory with the following content:
You can of course output anything in the representation template. As we are building a JSON representation in our example, the output should be valid JSON.
You don't have to send a content type header manually, Kirby will do this for you based on the representation type. Here, the response will automatically be sent with the content type
Now that we have a representation template for our
default template, we can request all
default pages as a JSON file. To access the representation, add the name of the representation to the end of the the URL.
https://yourdomain.com/about.json and so on.
If the representation exists, the template will be loaded and Kirby will send a correct content type header if possible. If the representation doesn’t exist, the error page will be displayed like if you didn’t use content representations at all.
It is still possible to create pages that contain a dot in their URL. If you already have a page called
about.json for some reason, it will continue to work. You can get the JSON representation of that page at
https://example.com/about.json.json. Please keep in mind though that using dots in URLs is not recommended to avoid confusion.
The built-in PHP server has issues with dots in paths, unless they are part of a filename, and will throw an error. For this reason, you may have to explore other local development solutions when working with content representations.
You can also have dedicated controllers for each of your representations. If you create a controller with the name
default.json.php, it will be used for the JSON representation of the default template. If no dedicated representation controller exists, the standard controller (
site.php) will be used instead (if available).
You can create content representations in plugins by defining a template with the matching extension.
If you need a matching controller, you can create one via a plugin as well:
Controllers and templates from plugins get overridden automatically if they exist in the
controllers directories. You can use this behavior to provide default setups in a plugin and still give the option to overwrite them individually if needed.