You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.4 KiB
62 lines
1.4 KiB
|
9 months ago
|
<?php
|
||
|
|
|
||
|
|
/**
|
||
|
|
* include_path
|
||
|
|
*
|
||
|
|
* uses a partial url, eg '/foo' to locate a corresponding
|
||
|
|
* php file, eg 'foo.php', and execute it.
|
||
|
|
*
|
||
|
|
* url_fragment - a key to locating php files, no extetension
|
||
|
|
letters and hyphens are ok
|
||
|
|
*/
|
||
|
|
function include_path($url_fragment) {
|
||
|
|
if (preg_match('#^/([a-z-]+.php)$#', $url_fragment, $matches)) {
|
||
|
|
$path = __DIR__ . '/../' . $matches[1];
|
||
|
|
} else {
|
||
|
|
$path = null;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (file_exists($path)) {
|
||
|
|
ob_start();
|
||
|
|
include $path;
|
||
|
|
$result = ob_get_clean();
|
||
|
|
|
||
|
|
return $result;
|
||
|
|
} else {
|
||
|
|
# Hard bail
|
||
|
|
http_response_code(404);
|
||
|
|
echo "404: $path not found\n";
|
||
|
|
exit;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* snippet_include
|
||
|
|
*
|
||
|
|
* loads non_php file for parsing.
|
||
|
|
* Uses {varname} to replace strings
|
||
|
|
*
|
||
|
|
* filename
|
||
|
|
* context - a keyed array for matching
|
||
|
|
* eg [ 'title'=>'Home Page', ... ]
|
||
|
|
*/
|
||
|
|
function snippet_include($filename, $context=[]) {
|
||
|
|
$snippet = file_get_contents($filename);
|
||
|
|
|
||
|
|
// Handle comments {* ... *}
|
||
|
|
$snippet = preg_replace('/ *{\*(.*?)\*}\n*/s','',$snippet);
|
||
|
|
|
||
|
|
// Use regex to find {placeholders} in the template
|
||
|
|
// Note this uses a callback function to do the matches
|
||
|
|
$snippet = preg_replace_callback('/\{\s*(\w+)\s*\}/', function($matches) use ($context) {
|
||
|
|
$key = $matches[1];
|
||
|
|
|
||
|
|
$value = isset($context[$key]) ? $context[$key] : $key;
|
||
|
|
|
||
|
|
return $value;
|
||
|
|
}, $snippet);
|
||
|
|
|
||
|
|
return $snippet;
|
||
|
|
}
|
||
|
|
|