-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleTemplate.php
More file actions
55 lines (47 loc) · 1.43 KB
/
SimpleTemplate.php
File metadata and controls
55 lines (47 loc) · 1.43 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
<?php declare(strict_types=1);
/**
* Part of Windwalker project.
*
* @copyright Copyright (C) 2019 LYRASOFT.
* @license GNU General Public License version 2 or later.
*/
namespace Windwalker\String;
use Windwalker\Utilities\ArrayHelper;
/**
* The SimpleTemplate class.
*
* @since 2.1.8
*/
abstract class SimpleTemplate
{
/**
* Parse variable and replace it. This method is a simple template engine.
*
* Example: The {{ foo.bar.yoo }} will be replace to value of `$data['foo']['bar']['yoo']`
*
* @param string $string The template to replace.
* @param array $data The data to find.
* @param array $tags The variable tags.
*
* @return string Replaced template.
*/
public static function render($string, $data = [], $tags = ['{{', '}}'])
{
$defaultTags = ['{{', '}}'];
$tags = (array) $tags + $defaultTags;
list($begin, $end) = $tags;
$regex = preg_quote($begin) . '\s*(.+?)\s*' . preg_quote($end);
return preg_replace_callback(
chr(1) . $regex . chr(1),
function ($match) use ($data) {
$return = ArrayHelper::getByPath($data, $match[1]);
if (is_array($return) || is_object($return)) {
return print_r($return, 1);
} else {
return $return;
}
},
(string) $string
);
}
}