Skip to content

Instantly share code, notes, and snippets.

@audinue
Created January 13, 2015 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audinue/bd96b17ee13c82ce8351 to your computer and use it in GitHub Desktop.
Save audinue/bd96b17ee13c82ce8351 to your computer and use it in GitHub Desktop.
Simple utility for template designers.
<?php
define('EXTENDS_PATTERN', '/\{extends ([a-z0-9_\/-]+)\}/');
define('BLOCK_PATTERN', '/\{block ([a-z0-9_-]+)\}([^\{]*)\{\/block\}/');
define('INCLUDE_PATTERN', '/\{include ([a-z0-9_\/-]+)\}/');
function tpl_compile($file) {
if(!is_file($file)) {
throw new Exception('File "' . $file . '" is not found.');
}
$string = file_get_contents($file);
if(preg_match(EXTENDS_PATTERN, $string, $match)) {
if(!is_file($match[1] . '.tpl.html')) {
throw new Exception('Base file "' . $match[1] . '.tpl.html" in "' . $file . '" is not found.');
}
$blocks = array();
preg_replace_callback(BLOCK_PATTERN, function($match) use (&$blocks) {
$blocks[$match[1]] = trim($match[2]);
}, $string);
$string = preg_replace_callback(BLOCK_PATTERN, function($match) use ($blocks) {
return $blocks[$match[1]];
}, file_get_contents($match[1] . '.tpl.html'));
}
return preg_replace(BLOCK_PATTERN, '$2', preg_replace_callback(INCLUDE_PATTERN, function($match) use ($file) {
if(!is_file($match[1] . '.tpl.html')) {
throw new Exception('Include file "' . $match[1] . '.tpl.html" in "' . $file . '" is not found.');
}
return trim(file_get_contents($match[1] . '.tpl.html'));
}, $string));
}
if(php_sapi_name() == 'cli') {
$dir = isset($argv[1]) ? $argv[1] : '.';
if(!is_dir($dir)) {
die('Target directory "' . $dir . '" is not found.');
}
foreach(glob('*.tpl.html') as $file) {
try {
file_put_contents($dir . '/' . preg_replace('/\.tpl\.html/', '.html', $file)
, tpl_compile($file));
} catch(Exception $e) {
die($e->getMessage());
}
}
exit;
}
if(isset($_GET['file'])) {
try {
if(realpath('.') != dirname(realpath($_GET['file']))) {
throw new Exception('Invalid file.');
}
echo tpl_compile($_GET['file']);
} catch(Exception $e) {
die($e->getMessage());
}
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TPL Files</title>
<meta charset="utf-8">
<style>
body {
font-family: arial, sans-serif;
font-size: 16px;
}
a {
color: #000;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
h1, li, p {
margin-bottom: 24px;
}
</style>
</head>
<body>
<h1>TPL Files</h1>
<ul>
<?php foreach(glob('*.tpl.html') as $file) { ?>
<li>
<a href="?file=<?php echo urlencode($file) ?>"><?php echo htmlspecialchars($file) ?></a>
</li>
<?php } ?>
</ul>
<p>January, 2015, with &#9829; by <a href="mailto:audinue@gmail.com">Audi Nugraha</a>.</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment