Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.

This is a dead-simple method of flexible templating for PHP-based websites.

Setup

.template.html

<html> <head> <title><!-- %TITLE --></title> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <style> BODY { text-align: center; font-size: 110%; } </style> </head> <body> <!-- %BODY --> </body> </html>

.template.php

<?php /** Stupid-simple Templating in PHP By Jonathan Overholt <jonathan@overholt.org> 2014 */ function _ProcessTemplate() { global $Template; global $TemplateFields; $TemplateFields['BODY'] = ob_get_contents(); ob_end_clean(); if(empty($Template) || empty($TemplateFields['BODY'])) { // Let's not waste time doing nothing } else { foreach($TemplateFields as $Field => $Value) { $Template = str_replace("<!-- %$Field -->", $Value, $Template); } print($Template); } } function SetTemplateField($Field, $Value) { global $TemplateFields; if($Value === NULL && isset($TemplateFields[$Field])) unset($TemplateFields[$Field]); else $TemplateFields[$Field] = $Value; } $Template = file_get_contents(dirname(__FILE__) . "/.template.html"); $TemplateFields['TITLE'] = ""; if(!empty($Template)) { ob_start(); register_shutdown_function('_ProcessTemplate'); } ?>

Usage

Usage is as simple as including .template.php at the top of each page.

Example 1

example.php

<?php require(".template.php"); SetTemplateField('TITLE','Welcome to my site!'); ?> <h1>Home</h1> <p>This page is simple and just serves as an example for the templating engine.</p> <hr /> <p>Thanks for visiting!</p>

Example 2

You can use whatever substitution fields you want in the templates. Just use SetTemplateField to set a value and it will be substituted for the tag when it occurs in the template.

.template.php

<html> <head> <title><!-- %TITLE --></title> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <style> BODY { text-align: center; font-size: 110%; } </style> <meta rel="author" content='<!-- %AUTHOR -->' /> </head> <body> <!-- %BODY --> </body> </html>

example2.php

<?php require(".template.php"); SetTemplateField('TITLE','Welcome to my site!'); SetTemplateField('AUTHOR','Jonathan Overholt'); ?> <h1>Home</h1> <p>This page is simple and just serves as an example for the templating engine.</p> <hr /> <p>Thanks for visiting!</p>
This page last updated: Thu Sep 18 15:27:50 2014 (GMT)