Edited for formatting. Wrapped code in three back ticks.
This time we’ll talk about “includes”. Includes are a way to pull in a file into the current file to reduce repetitive code or templates. Below we’ll show how to make a simple template and use it.
We use Includes in Xanadu which is open source: https://github.com/campsoftware/xanadu
Here’s Xanadu’s template for almost every page. It’ll look overwhelming, but broken down it’s a simple template as well. https://github.com/campsoftware/xanadu/blob/master/templates/page-resp.php
Last time we created a Hello World in an file called index.php.
<?php $buttonLabel = 'Hello'; $buttonJS = "alert('Hello World!');"; ?> <html><body> <button type="button" onclick="<?= $buttonJS ?>"><?= $buttonLabel ?></button> </body></html>
Let’s assume that our HTML rocks and it does everything we want, for now. Let’s split index.php into two files, template.htm and helloWorld.php.
<html><body> <button type="button" onclick="<?= $buttonJS ?>"><?= $buttonLabel ?></button> </body></html>
<?php $buttonLabel = 'Hello'; $buttonJS = "alert('Hello World!');"; ?>
Now we have two files but they are not working as a team yet. You can try loading them to see how they behave separated.
Our two files won’t work well until we Include the HTML into the PHP file.
<?php $buttonLabel = 'Hello'; $buttonJS = "alert('Hello World!');"; require_once( 'template.htm' ); ?>
Now our split HTML and PHP files are joined again using an Include from PHP. There are a few forms of Includes: include(), include_one(), require(), and require_once(). “Require” means the file must be there or it will produce an error. “Once” means only include it the first time, not every time it’s asked for.
Duplicate the helloWorld.php file and name the duplicate file to helloEarth.php. Then change the value of $buttonJS from “Hello World” to “Hello Earth”.
<?php $buttonLabel = 'Hello'; $buttonJS = "alert('Hello Earth!');"; require_once( 'template.htm' ); ?>
Now when you load:
- helloWorld.php you’ll see a Hello button that says Hello World
- helloEarth.php you’ll see a Hello button that says Hello Earth
You just created two PHP pages that both share a template.
Pretty easy, huh? Now think about a Web Store to show Products. All of the pages have the same format for the Title, Description, Photo, Comments, and such. This works because the same template but with different variable values.
I should say for a Products page you wouldn’t want to create one PHP page for each product. Instead you might have products.php and products.htm. To see a Widget, you could load something like “/products.php?id=widget” or “/products/widget”. I think that’ll be our next topic.!
Ask questions below. Some questions might end up being answered in another post.
CampSoftware Blog: https://campsoftware.com/blog/
Xanadu Info: https://campsoftware.com/products/xanadu.php
Xanadu Download: https://github.com/campsoftware/xanadu