Добавил макросы

This commit is contained in:
Федор Подлеснов 2015-12-10 16:09:22 +03:00
parent 7a5767f527
commit bb834a0f2d
3 changed files with 33 additions and 8 deletions

11
example3.php Normal file
View file

@ -0,0 +1,11 @@
<?php
$data = array('phedor', 'andrey');
require_once 'klein.php';
$tpl = new Klein();
$tpl->compile('template3.html');
echo $tpl->render(array('names' => $data));

View file

@ -6,21 +6,26 @@ class Klein {
function compile($html) {
$pattern = array_map(function ($grammar) {
list(, $result) = $grammar;
$body = strtr($grammar[0], [" " => "\s*", "+" => "\s+", ":var" => "(\w+(\s*\.\s*\w+)*)", ":id" => "(\w+)"]);
$body = strtr($grammar[0], [' ' => "\s*", '+' => "\s+", ':var' => "(\w+(\s*\.\s*\w+)*)", ':id' => "(\w+)"]);
return ["/$body/",
function ($x) use ($result) {
return "<?php " . preg_replace_callback("/#([\d\w]+)/", function ($s) use($x) {
return preg_replace("/\.\s*(\w+)/", "['$1']", $x[$s[1]]);
return "<?php " . preg_replace_callback("/#(\d+)(s?)/", function ($s) use($x) {
$pref = $s[2] == 's' ? '$' : '';
return implode(", ", array_map(function ($s) use($pref) { return $pref.preg_replace("/\.\s*(\w+)/", "['$1']", $s); }, preg_split("/\s*,\s*/", $x[$s[1]])));
}, $result) . " ?>";
}];
}, [
["{% for+:id+in+:var %}", "foreach(\$#2 as \$index => \$#1): \$loop = Klein::loop(\$index, \$#2);"],
["{% for+:id , :id+in+:var %}", "foreach(\$#3 as \$#1 => \$#2):"],
["{% for+:id+in+:var %}", "foreach(#2s as \$index => #1s): \$loop = Klein::loop(\$index, #2s);"],
["{% for+:id , :id+in+:var %}", "foreach(#3s as #1s => #2s):"],
["{% endfor %}", "endforeach;"],
["{% if+:var %}", "if(isset(\$#1) && \$#1 ):"],
["{% if+:var %}", "if(isset(#1s) && #1s):"],
["{% else %}", "else:"],
["{% endif %}", "endif;"],
["{{ :var }}", "echo \$#1;"],
["{{ :var\|:id }}", "echo #3(\$#1);"]
["{{ :var }}", "echo #1s;"],
["{{ :id\(( :var (, :var )*)?\) }}", "echo macro_#1(#2s);"],
["{{ :var\|:id }}", "echo #3(#1s);"],
["{% macro+:id\(( :id (, :id )*)?\) %}", "function macro_#1(#2s) {"],
["{% endmacro %}", "}"]
]);
$result = file_get_contents($html);

9
template3.html Normal file
View file

@ -0,0 +1,9 @@
<div>
{% macro hello(name) %}
<em>hello, {{ name }}<em>
{% endmacro %}
{% for name in names %}
{{ hello(name) }}
{% endfor %}
</div>