Немного документации

This commit is contained in:
Федор Подлеснов 2015-12-11 11:55:34 +03:00
parent bb834a0f2d
commit 999fe634de
3 changed files with 67 additions and 5 deletions

View file

@ -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 "<?php " . preg_replace_callback("/#(\d+)(s?)/", function ($s) use($x) {
$code = "<?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) . " ?>";
return ($x[0][2] == '!') ? "<!-- $code -->" : $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 %}", "}"]
]);

61
readme.md Normal file
View file

@ -0,0 +1,61 @@
#Простой шаблонизатор
#Переменные
Для переменной name=Андрей шаблон
```html
<b>Hello, {{ name }}</div>
```
преобразуется в
```html
<b>Hello, Андрей</div>
```
```html
<b>Hello, {{! name }} </div>
```
преобразуется в
```html
<b>Hello, <!-- Андрей --></div>
```
#Циклы
```html
<ul>
{% for user in users %}
<li>Hello, {{ user.name }}</li>
{% endfor %}
</ul>
```
#Условия
```html
<ul>
{% for user in users %}
{% if user.is_russian %}
<li>Привет, {{ user.name }}</li>
{% else %}
<li>Hello, {{ user.name }}</li>
{% endif %}
{% endfor %}
</ul>
```
#Макрос
```html
{% macro hello(user) %}
{% if user.is_russian %}
<li>Привет, {{ user.name }}</li>
{% else %}
<li>Hello, {{ user.name }}</li>
{% endif %}
{% endmacro %}
<ul>
{% for user in users %}
{% hello(user) %}
{% endfor %}
</ul>
```

View file

@ -1,6 +1,6 @@
<div>
{% macro hello(name) %}
<em>hello, {{ name }}<em>
<em>hello, {{ name }} {{! name }}<em>
{% endmacro %}
{% for name in names %}