Back to blog
Jul 2018·2 min readAI-translated

Simple Template Engine

#javascript#php#snippets#template#templateengine

For a somewhat larger project I was looking for a simple template engine. I didn't want to write the same code over and over for both my server-side and client-side scripts, which then also had to be changed awkwardly in two different places (keyword: single point of maintenance). A (emphasis!) simple template engine for PHP or JavaScript doesn't seem to exist, at least my search was unsuccessful. So the goal was to simply pass a few parameters to both a PHP file and a JavaScript, which would then replace the content of the template or file. For an Ajax request that is supposed to insert dynamic content into the page, I wanted to use the same "source" for the template as for a page build with PHP. If we have a forum, for example, that both displays posts (generated by a PHP script) and adds posts dynamically via JavaScript (for example when the post should be displayed right after submitting without reloading the page), without this template engine you would use two templates - once the template accessed by the PHP script, and once the template for the JavaScript. From now on you only need one template, used by both PHP and JavaScript. Variables are put in curly braces, which can of course be changed as desired. Long story short - an example:

<template source="welcome">
Hello, my name is {name} and I am {age} years old.
</template>

Here we want to replace {name} and {age} with variables that we can pass in dynamically. Let's go.

Le Javascript

<script language="javascript">
var TemplateEngine = function(tpl, data) {
	if ($("template[source='" + tpl + "']").length > 0){
		tpl = $("template[source='" + tpl + "']").html();
	}else{
		$.get(tpl, (data) => tpl = data);
	}
	var re = /{([^}]+)}/g, match;
	while(match = re.exec(tpl)){
		tpl = tpl.replace(match[0], data[match[1]]);
	}
	return tpl;
</script>

A call to the template engine now expects the template (tpl) and the data to be passed in. As the template we either specify the "source" property of an HTML node of type "template" that should be used as the template, or we give the relative path to the file containing the content of the template.

TemplateEngine("welcome", {name: 'David', age: 28})

Either we already have the template in the source code - then we access the element right away. Otherwise a GET request is started and the file is read via Ajax. As "tpl" we can therefore pass either a file name or the value of the "source" property of a node of type "template". The file then has to contain the above example, including the template node. As the return value we get

Hello, my name is David and I am 28 years old.

Le PHP

This should also be possible via PHP, otherwise everything would be pretty pointless and not usable for the desired purpose.

class TemplateEngine{
	public function compile($file, $data){
		preg_match_all('/<template([^>]*)>(.*)<\/template>/m', file_get_contents($file), $content, PREG_SET_ORDER, 0);
		$content = $content[0][2];
		foreach($data as $key => $value){
			$content = str_replace("{".$key."}", $value, $content);
		}
		return $content;
	}
}

You can call it simply via

$engine = new TemplateEngine();
$engine->compile("myfile.template", ["age" => "28", "name" => "David"]);

The return value is then likewise:

Hello, my name is David and I am 28 years old.

So now we only have to edit the template file and get the same output both server-side and client-side!

NewerSimple Image Resizing + CachingOlderConverting Seconds to Days, Hours, Minutes and Seconds