Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template inheritance with plain PHP

Tags:

php

I am building a small MVC app and I'd like to serve webpages that inherit from the base (i.e. parent) template. So, I've created a View.php class to initialize templates:

<?php

class View {

    protected $path = $_SERVER['DOCUMENT_ROOT'] . "views/";

    protected $data;

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

    public function render($view) {
        if ( file_exists($this->path.$view) )
            include $this->path.$view;
    }

    public function __set($name, $value) { $this->data[$name] = $value; }

    public function __get($name) { return $this->data[$name]; }
}

To load an independent template, I can do the following from routes.php:

$v = new View();
$v->people = ["josh", "alex", "michel"];
$v->render('welcome.php');

and welcome.php itself would be:

<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
    <?php print_r($this->people) ?>
</body>
</html>

Problem

This would work for independent webpages. What I want to do is implement template inheritance (just like in Twig or Blade), so that welcome.php can inherit from app.php. Here is what I am envisioning:

app.php (parent)

<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
    <header>...</header>
    <?php ***include('content')*** ?>
    <footer>...</footer>
</body>
</html>

welcome.php (child)

<?php ***extends('app.php')*** ?>

<?php ***block('content')*** ?>
    <h1>You made it to welcome.php!</h1>
<?php ***END block('content')*** ?>

How can I do this?

like image 703
Alex Avatar asked Jul 11 '26 08:07

Alex


1 Answers

To those interested, I was able to approximate template inheritance using this tutorial. It allows to bind variables both to parent and child templates, but it does not allow to overwrite more than one block in a single child template. So, you can't really have a section for content, styles, and scripts; you can only accomodate content; otherwise, you'd need to include markup from other PHP files. I am guessing this would require including custom tags and parsing them whem, but I didn't find a solution to this online. If anyone comes across a workaround, please let me know!

like image 89
Alex Avatar answered Jul 13 '26 13:07

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!