1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* TemplateEngine.php - Template engine |
5
|
|
|
* |
6
|
|
|
* Generate templates with template vars. |
7
|
|
|
* |
8
|
|
|
* @package jaxon-utils |
9
|
|
|
* @author Thierry Feuzeu <[email protected]> |
10
|
|
|
* @copyright 2022 Thierry Feuzeu <[email protected]> |
11
|
|
|
* @license https://opensource.org/licenses/BSD-3-Clause BSD 3-Clause License |
12
|
|
|
* @link https://github.com/jaxon-php/jaxon-core |
13
|
|
|
*/ |
14
|
|
|
|
15
|
|
|
namespace Jaxon\Utils\Template; |
16
|
|
|
|
17
|
|
|
use function trim; |
18
|
|
|
use function rtrim; |
19
|
|
|
|
20
|
|
|
class TemplateEngine |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* The default namespace |
24
|
|
|
* |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
protected $sDefaultNamespace = ''; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* The namespaces |
31
|
|
|
* |
32
|
|
|
* @var array |
33
|
|
|
*/ |
34
|
|
|
protected $aNamespaces; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Set the default namespace |
38
|
|
|
* |
39
|
|
|
* @param string $sDefaultNamespace |
40
|
|
|
* |
41
|
|
|
* @return void |
42
|
|
|
*/ |
43
|
|
|
public function setDefaultNamespace(string $sDefaultNamespace): void |
44
|
|
|
{ |
45
|
|
|
$this->sDefaultNamespace = $sDefaultNamespace; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Add a namespace to the template system |
50
|
|
|
* |
51
|
|
|
* @param string $sNamespace The namespace name |
52
|
|
|
* @param string $sDirectory The namespace directory |
53
|
|
|
* @param string $sExtension The extension to append to template names |
54
|
|
|
* |
55
|
|
|
* @return static |
56
|
|
|
*/ |
57
|
|
|
public function addNamespace(string $sNamespace, string $sDirectory, string $sExtension = ''): static |
58
|
|
|
{ |
59
|
|
|
$this->aNamespaces[$sNamespace] = [ |
60
|
|
|
'directory' => rtrim(trim($sDirectory), "/\\") . DIRECTORY_SEPARATOR, |
61
|
|
|
'extension' => $sExtension, |
62
|
|
|
]; |
63
|
|
|
return $this; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Render a template |
68
|
|
|
* |
69
|
|
|
* @param string $sTemplate The name of template to be rendered |
70
|
|
|
* @param array $aVars The template vars |
71
|
|
|
* |
72
|
|
|
* @return string |
73
|
|
|
*/ |
74
|
|
|
public function render(string $sTemplate, array $aVars = []): string |
75
|
|
|
{ |
76
|
|
|
$context = new Context($this->aNamespaces, $this->sDefaultNamespace, $sTemplate); |
77
|
|
|
return $context->__render($aVars); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|