When using HTML and CSS exclusively to build a large-scale website, things can quickly get out of hand: a simple coding mistake or typo could quickly multiply as one develops subsequent pages based on the erroneous HTML page. Fixing these errors can be a costly endeavor, and this often prompts one to ask: "Is there a way to write a piece of code once, and use it multiple times in different parts of the project?" This is where a modular approach to web development becomes essential.
While HTML remains a core component of any website, past and present, the technology remains largely primitive. One simply cannot combine multiple HTML "modules" into a single page using the browser alone, but server-side technologies such as PHP simplify this challenge.
PHP, featuring its inline style scripts, allows one to inject programming code into a simple HTML page. Using this logic, we can also choose to inject different HTML files into a parent HTML page using the include
function:
Consider the following PHP page (a simple HTML file with PHP extension):
...
<body>
<div id="header">
<a href="index.php">Homepage</a>
<a href="about.php">About</a>
<a href="contact.php">Contact</a>
</div>
<div id="content">
<h1>Welcome</h1>
<p>Hello world</p>
</div>
<div id="footer">
Work by John Doe
</div>
</body>
...
As one starts to build a larger website using the above page, one should be able to easily identify the repeating elements and create different HTML modules:
<div id="header">
<a href="index.php">Homepage</a>
<a href="about.php">About</a>
<a href="contact.php">Contact</a>
</div>
<div id="footer">
Work by John Doe
</div>
include
to inject HTML modulesOne can now come back to the original index.php file and take advantage of these newly created modules:
...
<body>
<? include "header.php" ?>
<div id="content">
<h1>Welcome</h1>
<p>Hello world</p>
</div>
<? include "footer.php" ?>
</body>
...
One can now continue creating subsequent pages, without having to manually repeat the same elements:
...
<body>
<? include "header.php" ?>
<div id="content">
<h1>About John Doe</h1>
<p>Lorem ipsum</p>
</div>
<? include "footer.php" ?>
</body>
...
While there are different approaches that one can take to using the include
function, one thing is clear: by converting a large, monolithic HTML page into a set of smaller modules, we can take better control over each project.