Skip to content

Instantly share code, notes, and snippets.

@jm42
Last active August 6, 2016 20:44
Show Gist options
  • Save jm42/3675fa8a2aa47d9c2aebd3ade9780255 to your computer and use it in GitHub Desktop.
Save jm42/3675fa8a2aa47d9c2aebd3ade9780255 to your computer and use it in GitHub Desktop.
Variable template in mustache style
<?php
function mustache(array $context) {
return function($resource) use($context) {
$handler = resource_of($resource);
$state = @out;
$tag = '';
while (!feof($handler)) {
$out = fgets($handler);
$len = strlen($out);
$pos = 0;
for ($i = $pos; $i < $len; $i++) {
if ($state === @out && $out[$i] === '{' && ($out[$i+1] ?? '') === '{') {
yield substr($out, $pos, $i - $pos);
$pos = $i + 2;
$tag = '';
$state = @tag;
} elseif ($state === @tag && $out[$i] === '}' && ($out[$i+1] ?? '') === '}') {
$tag = trim($tag . substr($out, $pos, $i - $pos));
$pos = $i + 2;
$state = @out;
switch ($tag[0]) {
default:
if (!isset($context[$tag])) {
throw new \RuntimeException("Variable \"$tag\" not found");
}
yield $context[$tag]; // TODO escape
}
}
}
if ($state === @out) {
yield substr($out, $pos);
} elseif ($state === @tag) {
$tag .= substr($out, $pos);
}
}
if ($state === @tag) {
throw new \LogicException('Unbalanced tags');
}
fclose($handler);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment