Search code examples
phptemplate-engine

Template engine disables PHP


So I build this template engine, but when I parse my files, it disables the php, which make me unable to get my sitename and stuff. This is the parser (rlly lightweight)

class Template {

    public  function __construct($directory) {
        $this->directory = $directory;
    }
public function getTemplate($filename) {
    $file = "app/themes/" . $this->directory . "/" . $filename . ".php";
    if(!file_exists($file)) {
        die("Het opgevraagde bestand bestaat niet.");
    } else {
        $this->content = file_get_contents($file);
        echo $this->content;
    }
}

}

Does anyone know a way to enable PHP again? By the way, I'm running this on my template:

$core->getSitename

Please note that this isn't any existing template engine.


Solution

  • Simply include the page (instead of loading it via file() etc.). If you do so, an output buffer comes in handy as well:

    public function getTemplate($filename) {
        $file = "app/themes/" . $this->directory . "/" . $filename . ".php";
        if(!file_exists($file)) {
            die("Het opgevraagde bestand bestaat niet.");
            //better to throw an error instead
        } else {
            ob_start();
            include $file;
            $this->content = ob_get_contents();
            ob_end_clean();
        }
    }
    

    There are alot of (good) template engines available for PHP. Instead of reinventing them, I'd suggest using one of them. However, if you still want to develop your own, look into their sources and find out how they solved problems you now face. A lot of thought and sweat went into their solutions.