diff --git a/example3.php b/example3.php new file mode 100644 index 0000000..fba906a --- /dev/null +++ b/example3.php @@ -0,0 +1,11 @@ +compile('template3.html'); + +echo $tpl->render(array('names' => $data)); diff --git a/klein.php b/klein.php index a7a01f7..82aad66 100644 --- a/klein.php +++ b/klein.php @@ -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 ""; }]; }, [ - ["{% 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); diff --git a/template3.html b/template3.html new file mode 100644 index 0000000..ff98917 --- /dev/null +++ b/template3.html @@ -0,0 +1,9 @@ +
+{% macro hello(name) %} + hello, {{ name }} +{% endmacro %} + +{% for name in names %} + {{ hello(name) }} +{% endfor %} +
\ No newline at end of file