From a993c96f332b926822c754d9cee8597dc5e78742 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A4=D0=B5=D0=B4=D0=BE=D1=80=20=D0=9F=D0=BE=D0=B4=D0=BB?= =?UTF-8?q?=D0=B5=D1=81=D0=BD=D0=BE=D0=B2?= Date: Tue, 1 Dec 2015 15:39:25 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=BD=D1=8B=D0=B5=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20=D1=82?= =?UTF-8?q?=D0=BE=D1=87=D0=BA=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 +++ example.php | 7 ++++-- klein.php | 67 +++++++++++++++++++++++++++++++++++++++-------------- 3 files changed, 57 insertions(+), 20 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..007b0c6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.bak +node_modules +temp \ No newline at end of file diff --git a/example.php b/example.php index 15cf792..75d9587 100644 --- a/example.php +++ b/example.php @@ -2,8 +2,11 @@ require_once 'klein.php'; -echo Klein::render('index.html', array( +$tpl = new Klein(); +$tpl->compile('index.html'); + +echo $tpl->render(array( 'style' => array('style.css'), - 'script' => array('script.js'), + 'script' => array(array('name' => 'script1.js'), array('name' => 'script2.js')), 'content' => 'test' )); \ No newline at end of file diff --git a/klein.php b/klein.php index 8e51bf2..9924a26 100644 --- a/klein.php +++ b/klein.php @@ -1,27 +1,58 @@ "", - "/{%\s*if\s+(\w+)\s*%}/" => "", - "/{%\s*block\s+(\w+)\s*%}/" => "", - "/{%\s*endblock\s*%}/" => "", - "/{%\s*endfor\s*%}/" => "", - "/{%\s*endif\s*%}/" => "", - "/{{\s*(\w+)\s*}}/" => "", - ); +class Klein { + private $code; + + function compile($html) { + $arg = function($name) { + $list = explode(".", $name); + $first = array_shift($list); + return "\$$first" . implode("", array_map(function($x) { return "['$x']"; }, $list)); + }; + + $var = "(\w+(\s*\.\s*\w+)*)"; + + list($for, $endfor, $if, $endif) = array_map( + function ($args) { + $body = implode($args, "\s*"); + return "/{%\s*$body\s*%}/"; + },[ + ['for', $var, 'in', $var], + ['endfor'], + ['if', $var], + ['endif'] + ]); + + $pattern = [ + $for => function ($x) use($arg) { + return ""; + }, + $endfor => function ($x) { + return ""; + }, + $if => function ($x) use ($arg) { + return ""; + }, + $endif => function ($x) { + return ""; + }, + "/{{\s*$var\s*}}/" => function ($x) use ($arg) { + return ""; + }, + ]; - $result = $data; + $result = file_get_contents($html); foreach($pattern as $key => $value) { - $result = preg_replace($key, $value, $result); + $result = preg_replace_callback($key, $value, $result); } - - extract($vars); - + + $this->code = $result; + } + + function render($vars) { + extract($vars); ob_start(); - eval(" ?>".$result."".$this->code."