Last active
January 6, 2024 18:30
-
-
Save mathiasrw/165a2e1ba43d79135fda69f6f0a16c24 to your computer and use it in GitHub Desktop.
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 | |
// Small hackable Mustache inspired templating | |
function alaMustache($template, array $values = []){ | |
$pattern = '/{{(?<BOOLEAN>#|\^)\s*(?P<KEY>[\w\.-]+)\s*}}(?P<BLOCK>.*?)({{\/\s*\2\s*}})/ms'; | |
$template = preg_replace_callback($pattern, function (array $matches) use ($values) { | |
if ($matches['BOOLEAN'] === '#') { | |
if (array_key_exists($matches['KEY'], $values) && !empty(trim($values[$matches['KEY']]))) { | |
return $matches['BLOCK']; | |
} | |
return ''; | |
} | |
if ($matches['BOOLEAN'] === '^') { | |
if (!array_key_exists($matches['KEY'], $values) || empty(trim($values[$matches['KEY']]))) { | |
return $matches['BLOCK']; | |
} | |
return ''; | |
} | |
return $matches[0]; | |
}, $template); | |
$pattern = '/{{{\s*(?P<KEY_HTML>[\w\.-]+)\s*}}}|{{\s*(?P<KEY>[\w\.-]+)\s*}}/m'; | |
$template = preg_replace_callback($pattern, function (array $matches) use ($values) { | |
if ($matches['KEY_HTML'] !== '' && array_key_exists($matches['KEY_HTML'], $values)) { | |
return $values[$matches['KEY_HTML']]; | |
} elseif ($matches['KEY'] !== '' && array_key_exists($matches['KEY'], $values)) { | |
return htmlspecialchars($values[$matches['KEY']], ENT_COMPAT | ENT_HTML5, 'UTF-8', false); | |
} | |
return $matches[0]; | |
}, $template); | |
return $template; | |
} | |
// echo alaMustache("{{ abc }} {{{abc}}} {{^ zzz}}yes{{/ zzz}} {{^abc}}ignore{{/abc }} {{# zzz}}and ignore{{/ zzz}} {{# abc}}and yes{{/ abc}}", ["abc"=>'0<br/>1']); | |
// result should be: | |
// 0 | |
// 1 0<br/>1 yes and yes | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment