How do I use PHP to create a basic templating system?

Creating a Basic Templating System with PHP

A templating system can greatly improve the maintainability and organization of your code, especially when working with larger projects. In this blog post, we will discuss how to create a basic templating system using PHP.

1. Creating a template file

To begin with, let’s create an HTML template file that will serve as the base structure for our pages. We will use placeholders wrapped in double curly braces (e.g., {{title}}) to denote areas where dynamic content will be inserted.

<!-- html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
</head>
<body>
    <header>
        <h1>{{header}}</h1>
    </header>
    <main>
        <p>{{content}}</p>
    </main>
    <footer>
        <p>{{footer}}</p>
    </footer>
</body>
</html>

2. Loading the template file

Next, we need to load the template file using PHP. In this example, we will assume that the template file is named “template.html”. We will use the file_get_contents() function to read the contents of the file into a variable:

<?php
# PHP
$template_file = 'template.html';
$template = file_get_contents($template_file);
?>

3. Replacing placeholders with dynamic content

Now that we have the template loaded, we can replace the placeholders with the actual content we want to display. For this, we will create a simple function called “render()” that accepts an associative array containing the keys and values to replace the placeholders.

<?php
# PHP
function render($template, $data) {
    foreach ($data as $key => $value) {
        $template = str_replace("{{" . $key . "}}", $value, $template);
    }
    return $template;
}
?>

4. Rendering the final output

Finally, we can use the render() function to generate the final output by passing the template and an associative array containing the keys and values to replace the placeholders. Then, we’ll echo the result to display the final rendered HTML.

<?php
# PHP
$data = [
    'title' => 'My Blog',
    'header' => 'Welcome to My Blog',
    'content' => 'This is a simple blog created using a basic PHP templating system.',
    'footer' => '© 2023 My Blog'
];

echo render($template, $data);
?>

Conclusion:

In this blog post, we have discussed how to create a basic templating system using PHP. By creating a template file, loading it with PHP, replacing placeholders with dynamic content, and rendering the final output, you can easily create and maintain a more organized codebase. Keep in mind that this is a very basic example, and for more complex projects, you may want to consider using an existing templating engine like Twig or Smarty.

Got question?

Submit it here

© All rights reserved.