Search code examples
phptemplatesdirectory-structure

How to make a PHP template without a database?


I'm working on a small company "brochure" website. I have a few pieces that repeat for example:

  • Menu
  • Submenu
  • Footer
  • Subheader

Say a page "comparison.php" needs to have all of the above and then content. I could do which is how I started:

<?php include '/partial/menu.php'; ?>

<p>This is a product comparison</p>
<figure>
  <figcaption>Probably an image here</figcaption>
  ((image))
</figure>
<table>
  <tr><td>Product 1</td><td>Product 2</td></tr>
  <tr><td>Point A</td><td>Point B</td></tr>
</table>

<?php include '/partial/footer.php'; ?>

I'm thinking what a better way might be. Perhaps adding a directory content so then it becomes:

<?php include '/partial/menu.php'; ?>

<?php include '/content/comparison.php'; ?>

<?php include '/partial/footer.php'; ?>

This still feels clunky to me especially when I've got multiple subheaders and submenus depending on the page.

I've read online about templates with PHP but everything is with databases just inserting variables like, Programmers.SE - How to structure template system using plain PHP How would I go about streamlining this as much as possible without using a database? And please do not tell me to use a CMS, it's not an option.


Solution

  • Alright I think I figured out a methodology that is quite nice.

    3 Main Files being used:

    1. comparison.php
    2. information_template.php
    3. content/comparison.php

    comparison.php

    <?php
    $pagename = 'comparison';
    
    include('information_template.php');
    ?>

    information_template.php

    <?php include '/content/' . $pagename . '.php'; ?>

    content/comparison.php

    All of the content goes here

    Now I can just make a page in my root and a page in the content for each one with the same format and it should work. I'll probably add some additional to comp.php something like $pagetype = 'information'; or $pagetype = 'review'; so I can then add to my information_template.php:

    <?php include '/partial/' . $pagetype . '-subheader.php'; ?>
    <?php include '/partial/' . $pagetype . '-toc.php'; ?>