DEV Community

Cover image for PHP - Create your own PHP template engine
F.R Michel
F.R Michel

Posted on

PHP - Create your own PHP template engine

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Easy to use:

$template = new Template('var/www/html/project/template', []);
echo $template->render('home-page.php');
Enter fullscreen mode Exit fullscreen mode

With parameters:

$template = new Template('var/www/html/project/template', ['lang' => 'fr']);
echo $template->render('home-page.php', ['title' => 'Home Page']);
Enter fullscreen mode Exit fullscreen mode
<!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>
Enter fullscreen mode Exit fullscreen mode

https://github.com/devcoder-xyz/php-template-engine

Top comments (0)