I am Working on a little project and I want to apply some sort of templating to display content in between a master template file when included on each page without using any templating engine. Currently i have the following pages.
layout.template.php
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<!-- page content displays here -->
<?php show_content(); ?>
</body>
</html>
index.php
<?php function show_content(){ ?>
<div>
<h1>Home page</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<?php }
include 'layout.template.php';
?>
second.php
<?php function show_content(){ ?>
<div>
<h1>Second page</h1>
<p>some other content</p>
</div>
<?php }
include 'layout.template.php';
?>
i use the show_content() function to define the html that would be rendered into the layout.template.php file on each page. When layout.template.php is include it makes a call to the function and displays the html code in it based on the page it is included it. my question is
Is this a good idea or practice? What alternative do i have to achieving this (other than using templating engines)?
There is not a perfect answer, because there are too many ways how to do it.
A good solution would be to separate the view (HTML) from the logic (PHP). Probably MVC would be a good answer.
If you want to practice only:
Create a folder and put all your HTML files into that folder. Then you have your PHP file which includes a function (or maybe even a method) that calls that HTML content which you would like to display. If your HTML content also includes PHP, it would be better not to name it myFile.php
. In this case call it myFile.phtml
, so that it is clear to your, it is HTML but part of it is PHP as well.