-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.php
More file actions
88 lines (69 loc) · 2.38 KB
/
template.php
File metadata and controls
88 lines (69 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/**
* Created by PhpStorm.
* User: menakafernando
* Date: 7/12/18
* Time: 10:29 AM
*/
class Template {
private $vars = array();
public $path;
public $content;
private $valid = false;
public $stack = array();
public $final;
function __construct($template_name) {
$this->path = $template_name . '.tmpl';
if (file_exists($this->path)){
$this->content = file_get_contents($this->path);
$this->valid = true;
} else{
exit('<h3>Template Error!!</h3>');
}
}
public function replace($str) {
if (isset($this->vars[$str])) {
echo $this->vars[$str];
} else {
echo '{{' . $str . '}}';
}
}
public function wrap($arr, $main_arr, $count) {
$this->stack[] = $this->vars;
if ($count == sizeof($main_arr)) {
$this->final = true;
}else{
$this->final = false;
}
foreach ($arr as $k => $v) {
$this->vars[$k] = $v;
}
}
public function lastElem($con) {
if($con == '@last') {
if($this->final){
return false;
}
return true;
}
return false;
}
public function unwrap() {
$this->vars = array_pop($this->stack);
}
public function render() {
if($this->valid){
$this->content = preg_replace('/\{\{#unless (@\w+)\}\}/', '<?php if ($this->lastElem(\'$1\')): ?>', $this->content);
$this->content = preg_replace('/\{\{else\}\}/', '<?php else : ?>', $this->content);
$this->content = preg_replace('/\{\{\/unless\}\}/', '<?php endif; ?>', $this->content);
$this->content = preg_replace('/[\n\r]/','<br>', $this->content );
$this->content = preg_replace('/\{\{(\w+)\}\}/', '<?php $this->replace(\'$1\'); ?>', $this->content);
$this->content = preg_replace('/\{\{#each (\w+)\}\}/', '<?php $loop = $this->vars[\'$1\'];$count = 0; foreach ($this->vars[\'$1\'] as $arr): $count++; $this->wrap($arr, $loop, $count); ?>', $this->content);
$this->content = preg_replace('/\{\{\/each\}\}/', '<?php $this->unwrap(); endforeach; ?>', $this->content);
eval(' ?> '. $this->content .' <?php ');
}
}
public function assign($key, $value) {
$this->vars[$key] = $value;
}
}