Pages and Layouts
The special files layout.php
, index.php
allow you to create UI for a route. This page will guide you through how and when to use these special files.
Pages
A index is UI that is unique to a route. You can define a page by creating index.php file.
For example, to create your index page, add the index.php file inside the app directory:
app/index.php
<?php
echo "Hello, World! from app/index.php";
Then, to create further pages, create a new folder and add the index.php
file inside it. For example, to create a page for the /dashboard
route, create a new folder called dashboard
, and add the index.php
file inside it:
app/dashboard/index.php
<?php
echo "Hello, World! from app/dashboard/index.php";
- A page is always the leaf of the route subtree.
- A index.php file is required to make a route segment publicly accessible.
- Pages are Server Components by default, but can be set to a Client Component.
- Pages can fetch data. View the Data Fetching section for more information.
Layouts
A layout is UI that is shared between multiple routes. On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be nested.
You can define a layout by creating layout.php
file. The file should accept a children
content that will be populated with a child layout (if it exists) or a page during rendering.
app/dashboard/layout.php
<section>
<!-- Include shared UI here e.g. a header or sidebar -->
<?= MainLayout::$childLayoutChildren; ?>
</section>
Root Layout (Required)
The root layout is defined at the top level of the app directory and applies to all routes. This layout is required and must contain html and body tags, allowing you to modify the initial HTML returned from the server.
app/layout.php
<html lang="en">
<!-- head -->
<body>
<main><?= MainLayout::$children; ?></main>
</body>
</html>
Nesting Layouts
By default, layouts in the folder hierarchy are nested, which means they wrap child layouts via their children
content. You can nest layouts by adding layout.php
inside specific route segments (folders).
For example, to create a layout for the /dashboard
route, add a new layout.php file inside the dashboard folder:
app/dashboard/layout.php
<section>
<?= MainLayout::$childLayoutChildren; ?>
</section>
If you were to combine the two layouts above, the root layout (app/layout.php
) would wrap the dashboard layout (app/dashboard/layout.php
), which would wrap route segments inside app/dashboard/*
.
The two layouts would be nested as such:
- Only the root layout can contain <html> and <body> tags.
- Layouts can fetch data. View the Data Fetching section for more information.
- Layouts do not have access to the route segments below itself.
- You can use Route Groups to opt specific route segments in and out of shared layouts.
- You can use Route Groups to create multiple root layouts. See an example here.