Ideal for small project :
<?php
namespace DevCoder;
/**
* Class Template
* @package DevCoder
*/
class Template
{
/**
* @var string
*/
private $path;
/**
* @var array
*/
private $parameters = [];
/**
* Template constructor.
* @param string $path
* @param array $parameters
*/
public function __construct(string $path, array $parameters = [])
{
$this->path = rtrim($path, '/').'/';
$this->parameters = $parameters;
}
/**
* @param string $view
* @param array $context
* @return string
* @throws \Exception
*/
public function render(string $view, array $context = []): string
{
if (!file_exists($file = $this->path.$view)) {
throw new \Exception(sprintf('The file %s could not be found.', $view));
}
extract(array_merge($context, ['template' => $this]));
ob_start();
include ($file);
return ob_get_clean();
}
/**
* @param string $key
* @return mixed
*/
public function get(string $key)
{
return $this->parameters[$key] ?? null;
}
}
Easy to use:
$template = new Template('var/www/html/project/template', []);
echo $template->render('home-page.php');
With parameters:
$template = new Template('var/www/html/project/template', ['lang' => 'fr']);
echo $template->render('home-page.php', ['title' => 'Home Page']);
<!doctype html>
<html lang="<?php echo $template->get('lang'); ?>">
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
...
<!-- Le reste du contenu -->
...
</body>
</html>
Top comments (0)