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."