I tried writing my very first template engine today. I designed it to just replace variables in templates, and keep it basic for now. Can anyone give me some constructive criticism?
I'm getting ready to write my own mini framework, and want to improve as much as I can. I just need to know if this is the default way (logic) to write one, or is there a better way?
<?php
class Template {
public $variables = [];
public function assign($key, $value) {
$this->variables[$key] = $value;
}
public function render($template, $variables = []) {
if (empty($variables)) {
$variables = $this->variables;
}
$code = file_get_contents($template);
foreach ($this->variables as $key => $variable) {
$code = str_replace('%' . $key . '%', $this->variables[$key], $code);
}
return $code;
}
}
1 Answer 1
This template is either unusable or would make you write HTML in the business logic part spoiling the whole idea.
A template engine is a more complex application than people often think. There is always a presentation logic that could be quite complex. Which means a template must support programming statements. At least loops and conditions. Without them, it will be almost unusable.
Imagine you need to list 10 posts an a blog. How it could be done in your template? Going to add all the HTML formatting to variables before assigning them? Really?
So, such a simple template could be made viable only by letting PHP to interpret the template. So it could be like
public function render($template, $variables = []) {
array_merge($this->variables, $variables);
extract($variables)
ob_start();
include $template;
return ob_get_clean();
}
this way you will be able to use full featured templates that will contain all the logic needed for the presentation of your data.
assign()
method, but supply some more variable torender()
at the same time? Why not merge the two arrays so you can use both? \$\endgroup\$