Четные и нечетные элементы в циклах
This commit is contained in:
parent
3f5d4a5e9c
commit
7a5767f527
2 changed files with 11 additions and 3 deletions
12
klein.php
12
klein.php
|
|
@ -9,12 +9,12 @@ class Klein {
|
|||
$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+)/", function ($s) use($x) {
|
||||
return "<?php " . preg_replace_callback("/#([\d\w]+)/", function ($s) use($x) {
|
||||
return preg_replace("/\.\s*(\w+)/", "['$1']", $x[$s[1]]);
|
||||
}, $result) . " ?>";
|
||||
}];
|
||||
}, [
|
||||
["{% for+:id+in+:var %}", "foreach(\$#2 as \$index => \$#1): \$loop = ['first' => \$index == 0, 'last' => \$index == count(\$#2) - 1];"],
|
||||
["{% for+:id+in+:var %}", "foreach(\$#2 as \$index => \$#1): \$loop = Klein::loop(\$index, \$#2);"],
|
||||
["{% for+:id , :id+in+:var %}", "foreach(\$#3 as \$#1 => \$#2):"],
|
||||
["{% endfor %}", "endforeach;"],
|
||||
["{% if+:var %}", "if(isset(\$#1) && \$#1 ):"],
|
||||
|
|
@ -31,6 +31,14 @@ class Klein {
|
|||
$this->code = $result;
|
||||
}
|
||||
|
||||
static function loop($idx, &$array) {
|
||||
$is_even = $idx % 2;
|
||||
return ['first' => $idx == 0
|
||||
, 'last' => $idx == count($array) - 1
|
||||
, 'odd' => !$is_even
|
||||
, 'even' => $is_even];
|
||||
}
|
||||
|
||||
function render($vars) {
|
||||
extract($vars);
|
||||
ob_start();
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
<div>
|
||||
{% for var in content %}
|
||||
{% for key, value in var %}
|
||||
{{key}} - {{value}}
|
||||
<b>{{key}} - {{value}}</b>
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
Loading…
Add table
Add a link
Reference in a new issue