PHP - Create your own PHP template engine

fadymr

F.R Michel

Posted on November 16, 2020

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

💖 💪 🙅 🚩
fadymr
F.R Michel

Posted on November 16, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related