Created
July 29, 2012 03:32
-
-
Save yhirose/3195927 to your computer and use it in GitHub Desktop.
PHP tiny mustache implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# Simple Mustache template engine | |
function render($tmpl, $params) { | |
return preg_replace_callback( | |
'/(?:\{\{(\w+)\}\}|\{\{\{(\w+)\}\}\})/', | |
function($m) use($params) { | |
if (isset($params[$m[1]])) { | |
return htmlspecialchars($params[$m[1]]); | |
} else if (isset($params[$m[2]])) { | |
return $params[$m[2]]; | |
} else { | |
return $m[0]; | |
} | |
}, | |
$tmpl); | |
} | |
$tmpl = <<<EOS | |
{{#list}} | |
>>> {{{key0}}} {{key1}} <<< | |
{{/list}} | |
EOS; | |
$params = array( | |
array('key0' => '<b>item0</b>', 'key1' => '<b>orz...</b>'), | |
array('key0' => '<b>item1</b>', 'key1' => '<b>orz...</b>') | |
); | |
var_dump(render($tmpl, $params)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment