#38 - Simple PHP Template Class

Data: 2018-12-08 12:00 - PHP

PHP class that allows you to load templates and replace strings in that template.

<?php
class Template {
    private $template;
    private $replacements = array();

    public function __construct($template) {
        $this->template = $template;
    }

    public static function fromFile($file) {
        return new Template(file_get_contents($file));
    }

    public function replace($id, $value) {
        $this->replacements[$id] = $value;
    }

    public function dump($return = false) {
        $toDump = $this->template;
        foreach ($this->replacements as $id => $value)
            $toDump = str_replace('{{' . $id . '}}', $value, $toDump);
        $toDump = preg_replace('/{{[A-z\-]*}}/', '', $toDump);

        if ($return)
            return $toDump;

        echo $toDump;
    }
}

Previous snippet | Next snippet