diff --git a/klein.php b/klein.php index 82aad66..bd3d242 100644 --- a/klein.php +++ b/klein.php @@ -6,13 +6,14 @@ 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 ""; + return ($x[0][2] == '!') ? "" : $code; }]; }, [ ["{% for+:id+in+:var %}", "foreach(#2s as \$index => #1s): \$loop = Klein::loop(\$index, #2s);"], @@ -22,9 +23,9 @@ class Klein { ["{% else %}", "else:"], ["{% endif %}", "endif;"], ["{{ :var }}", "echo #1s;"], - ["{{ :id\(( :var (, :var )*)?\) }}", "echo macro_#1(#2s);"], + ["{{ :id \(( :var (, :var )*)?\) }}", "echo macro_#1(#2s);"], ["{{ :var\|:id }}", "echo #3(#1s);"], - ["{% macro+:id\(( :id (, :id )*)?\) %}", "function macro_#1(#2s) {"], + ["{% macro+:id \(( :id (, :id )*)?\) %}", "function macro_#1(#2s) {"], ["{% endmacro %}", "}"] ]); diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..c75f5d8 --- /dev/null +++ b/readme.md @@ -0,0 +1,61 @@ +#Простой шаблонизатор + +#Переменные + +Для переменной name=Андрей шаблон +```html +Hello, {{ name }} +``` +преобразуется в +```html +Hello, Андрей +``` + +```html +Hello, {{! name }} +``` +преобразуется в +```html +Hello, +``` + +#Циклы + +```html +
    + {% for user in users %} +
  • Hello, {{ user.name }}
  • + {% endfor %} +
+``` + +#Условия + +```html +
    + {% for user in users %} + {% if user.is_russian %} +
  • Привет, {{ user.name }}
  • + {% else %} +
  • Hello, {{ user.name }}
  • + {% endif %} + {% endfor %} +
+``` + +#Макрос + +```html +{% macro hello(user) %} + {% if user.is_russian %} +
  • Привет, {{ user.name }}
  • + {% else %} +
  • Hello, {{ user.name }}
  • + {% endif %} +{% endmacro %} +
      + {% for user in users %} + {% hello(user) %} + {% endfor %} +
    +``` \ No newline at end of file diff --git a/template3.html b/template3.html index ff98917..f5fa1f2 100644 --- a/template3.html +++ b/template3.html @@ -1,6 +1,6 @@
    {% macro hello(name) %} - hello, {{ name }} + hello, {{ name }} {{! name }} {% endmacro %} {% for name in names %}