Layout and partial logic
Learn to build a page layout by combining header, footer and content partials.
Partial and layout logic
A partial is a small piece of PHP/HTML written to be included into other files. It is not run on its own; it is called inside a layout (page skeleton).
A typical page has three partials: header.php (top header and menu), content.php (the main content) and footer.php (the bottom info). The main page calls these partials in order with include. This way all pages share the same header and footer; a change is made in one place. This pattern shows up everywhere from small sites to large frameworks.
Combining partials in a layout
To build a layout, the main file calls the partials in order with include or require. The header partial opens <html>, <head>, <body> and the menu; the footer partial closes them.
The content partial sits in between. Example: include __DIR__ . '/partials/header.php';, then content, then include __DIR__ . '/partials/footer.php';. Building paths with __DIR__ works even when partials live in different folders. You can share variables like $title with the content partial, because an included file sees the caller's scope.
Exercise Combine header and footer partials in a layout
Assign sys_get_temp_dir() to $dir. Create two partial files with file_put_contents($dir . "/header.php", "<?php echo 'HEADER'; ?>") and file_put_contents($dir . "/footer.php", "<?php echo 'FOOTER'; ?>"). Then write, in order, include $dir . "/header.php";, echo " CONTENT ";, include $dir . "/footer.php";.
Show example solution
First set $dir = sys_get_temp_dir();. Write the header.php and footer.php partials with file_put_contents. Then add include $dir . "/header.php";, echo " CONTENT ";, include $dir . "/footer.php";.
Example solution:
<?php
// Create header and footer partials and combine in a layout
$dir = sys_get_temp_dir();
file_put_contents($dir . "/header.php", "<?php echo 'HEADER'; ?>");
file_put_contents($dir . "/footer.php", "<?php echo 'FOOTER'; ?>");
include $dir . "/header.php";
echo " CONTENT ";
include $dir . "/footer.php";
Test yourself
-
What is a partial file?
- A full page that runs on its own
- A piece of code included into other files
- A file that only contains HTML
- A temporarily created file
Show answer
A piece of code included into other files — Correct. A partial is a small piece of code written to be included into other files.
-
Complete the layout partial
include __DIR__ . '/partials/____.php';Show answer
include __DIR__ . '/partials/footer.php'; -
Match partials to their roles
- header.php
- Top header and menu
- content.php
- Main page content
- footer.php
- Bottom info
- sidebar.php
- Side panel