Last updated 2023-05-09 15:13:38

Simple PHP Templating Engine

In this article, I will share two ways you can implement a simple templating engine in PHP. The focus is on data templating and does not include implementation for looping and handling conditions.

Inbuilt templating

PHP comes with an inbuilt templating syntax you can use.

01: <?php 02: 03: $who = 'Eddymens'; 04: $did = 'came'; 05: $what = 'home'; 06: 07: ?> 08: 09: <?= $who ?> <?= $did ?> <?= $what ?>

The use of this templating syntax was very common circa web frameworks. This syntax however requires that the entire file is executed as a PHP file. Thus if your app requires the end user to use templates (e.g.: email templating) you might run into challenges as you wouldn't want them to be able to execute PHP code on your server.

For this, you will want to implement a custom PHP-free templating engine.

PHP free templating

What if you want a templating engine free of PHP syntax? Then you can turn to strtr [↗].

01: <?php 02: 03: function templateEngine($template, $data) { 04: $templateKeys = array_map(function($val) { return '{{'.$val.'}}';} , 05: array_keys($data)); 06: 07: $processedData = array_combine($templateKeys, array_values($data)); 08: return strtr($template,$processedData); 09: } 10: 11: $data = [ 12: 'who' => 'Eddymens', 13: 'did' => 'came', 14: 'what' => 'home' 15: ]; 16: 17: $template = "{{who}} {{did}} {{what}}"; 18: 19: echo templateEngine($template, $data); 20: ?>

In the above code, we create a function templateEngine that takes the data the user provides in the form of an array then passes it to strtr to replace every instance of the key with the data itself.

On line 04 the provided keys are wrapped between curly braces {{}}, before the entire array is passed to the strtr function. If this is not done there will be no matches since the function will be looking to replace the raw key instead of the template version. For example, searching for who instead of {{who}}.

Here is another article you might like 😊 "Snippet injection not working on Netlify"