How to implement Template Inheritance (like Django?) in PHP5
Asked Answered
M

10

13

Is there an existing good example, or how should one approach creating a basic Template system (thinking MVC) that supports "Template Inheritance" in PHP5?

For an example of what I define as Template Inheritance, refer to the Django (a Python framework for web development) Templates documentation: http://docs.djangoproject.com/en/dev/topics/templates/#id1

I especially like the idea of PHP itself being the "template language", though it's not necessarily a requirement.

If listing existing solutions that implement "Template Inheritance", please try to form answers as individual systems, for the benefit of 'popular vote'.

Michaelson answered 3/6, 2009 at 19:20 Comment(1)
old question, but the code snippets here are a perfect example of doing PHP template inheritance using no templating language and just the good ol' ob_start() and ob_get_clean(): symfony.com/doc/current/book/from_flat_php_to_symfony2.htmlOpisthognathous
F
0

The PHP language itself was designed for just these tasks, [unfortunately] it became capable of more and more over time and people who had started out with that simple syntax started implementing more and more complex tasks with that strangely evolved language.

I think what you mean with template inheritance is best expressed as dynamic file inclusion in PHP, as simple as

<? require $content ?>
Farceuse answered 3/6, 2009 at 19:38 Comment(2)
Using this solution is possible because all variables defined in a parent (or "controller") PHP script are available "globally" to all includes, and files included by those includes as well, correct?Michaelson
That is correct, the scope stays the same if you include a file. You can even access $this if you include a file from within a class method.Farceuse
B
18

Sorry to dig up an old thread, but I just released a library that does template inheritance in native PHP. Very inspired by Django. Please check it out and let me know what you think:

"PHP Template Inheritance"

http://arshaw.com/phpti/

Badr answered 29/3, 2010 at 1:4 Comment(1)
As it's no longer maintained, do you know any alternatives? Thanks.Inkblot
S
9

The answer Soulmerge gave has nothing to do with template inheritance.

Personally, I think template inheritance is great, and this is my first time seeing anyone complain about it.

phpti is one option pointed out earlier, but it looks a bit ugly to me.

You might want to consider mustache (mustache.github.com), which supports template inheritance, and has implementations in many languages (including php). To use mustache templates in PHP, you would probably want to write a controller of some sort to read in the mustache files and process them.

Ski answered 10/5, 2012 at 9:41 Comment(0)
T
4

Symfony supports template inheritance, it looks so much like django that the syntax looks compatible with django or other beautiful jinja python engines.

Elegance, like using PHP as a template language:

<h1><?php echo $page->title; ?></h1>
<?php foreach($page->comments as $comment): ?>
    <?php echo $comment->body; ?>
<?php endforeach; ?>
<?php echo $page->comments->count(); ?>

Or even more elegant, jinja:

<h1>{{ page.title }}</h1>
{% for comment in page.comments %}
   {{ comment.body }}
{% endfor %}
{{ page.comments.count %}
Trapezohedron answered 10/7, 2009 at 2:10 Comment(3)
This should be a comment on the original post/question.Michaelson
@Trapezohedron can you repost the content linked above (the link is dead now). I really want to hear some sound arguments against template inheritance in PHP, since this is how I plan to structure templates on a new project if I don't find any counter-arguments. Especially since I finally realized that no templating engine is needed: PHP has ob_start() and ob_get_clean() and these are all it's needed for "clean" inheritance (an example being the basic snippets here: symfony.com/doc/current/book/from_flat_php_to_symfony2.html)Opisthognathous
For template inheritance in Symfony, please refer to the link in the above (updated) answer. Output buffering is useful if you really want to use the PHP language as your template language but that's not recommended (see above answer update).Trapezohedron
T
2

Both the Smarty and Twig templating systems support "Template inheritance" as found in django's templating system. Both of these are popular and well supported templating systems however, twig has a syntax closer to django and so you may be more comfortable using this.

Smarty

To do this in smarty you can do so as in the following example, copied from the Smarty Documentation on Inheritence

layout.tpl

<html>
<head>
  <title>{block name=title}Default Page Title{/block}</title>
</head>
<body>
{block name=body}{/block}
</body>
</html>

mypage.tpl

{extends file="layout.tpl"}
{block name=title}My Page Title{/block}
{block name=body}My HTML Page Body goes here{/block}

output of mypage.tpl

<html>
<head>
  <title>My Page Title</title>
</head>
<body>
My HTML Page Body goes here
</body>
</html>

Twig

Again, there is great documentation for the use of this feature. In the twig documentation the example is more complex in order to demonstrate some of the more advanced features provided by twig but for comparative purposes I have written something which mirrors the smarty example in twig.

layout.twig

<html>
<head>
  <title>{% block title %}Default Page Title{% endblock %}</title>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>

mypage.twig

{% extends layout.twig %}
{% block title %}My Page Title{% endblock %}
{% block body %}My HTML Page Body goes here{% endblock %}

Conclusion

In retrospect, both examples are almost identical and so choosing between the two is a matter of comparing the features and a completely different question. Using a PHP template framework you are able to achieve template inheritance much like how it is done with django.

Further Reading

Tunis answered 8/1, 2015 at 8:48 Comment(2)
+1 for your post. But I would like to know in your opinion if template inheritance can be done easily in php without a template engine?Faggot
@Faggot I have seen some attempts at template inheritance in the past but it is all a little hacky. Simply put the way it would work is that you have your page working as the controller (e.g. index.php) and then at the end of your code you can include template.php. Within the template you can make calls to functions that would output the sections (similar to the blocks above) which can be overridden by including other template files that define these functions. It gets complicated and messy with order of file inclusion being important and undefined function errors to be handled.Tunis
C
1

Assuming you are familiar with how class inheritance works, your answer is YES, PHP supports it. The django thing might be overkill, but I'll try and fill you in real quick on how to do it anyways.

Note: I'm not going into using a controller here. Obviously if the page is a blog, you are going to create a blogPage object rather than just a regular Page. ALSO, I wrote this up from scratch for you, so no guarantees on it working.. but hopefully it will give you some ideas.

<?php
class Page
{

    protected $content_main; // Your main page content.
    protected $content_leftbar; // Your left sidebar content.
    protected $content_title; // Your content title.
    protected $template; // Template data.

    Function getTemplate() {
        // Logic for determining the template to be used in here.
        // Let's say it returns the location of a cached version of the template.
            return $template_file_path;
    }

    Function populateContentBlocks() {
        // This populates the $content_BLOCK variables with data using some default
        // logic you have for determining where to grab that data from.
    }

    Function loadPage() {

        // Populates variables.
        $this->populateContentBlocks();

            // Fetches template
        include( $this->getTemplate() );
    }


} // END class


Class blogPage extends Page {
    Function getTemplate() {
        // Logic for determining the template to be used in here.
        // Let's say it returns the location of a cached version of the template.
        // OVERRIDE THE DEFAULT TEMPLATE LOGIC OF THE PAGE WITH WHAT IS RELEVENT TO
                // BLOGPAGE.
    }
}
?>

Template File Example:

<html>
  <head>
    <title><?php echo $this->content_title; ?></title>
  </head> 

  <body>
      <div class="sidebar"><?php echo $this->content_sidebar; ?></div>
      <div class="mainContent"><?php echo $this->content_main; ?></div>
  </body>
</html>
Chatelaine answered 3/6, 2009 at 21:32 Comment(2)
Yeah, loadpage should just be loadPage() { $this->populateBlocks(); include $this->templateFile; }Ovoviviparous
Doh, too much c++, I haven't been doing php for a while. Thanks for the reminder.Chatelaine
F
0

The PHP language itself was designed for just these tasks, [unfortunately] it became capable of more and more over time and people who had started out with that simple syntax started implementing more and more complex tasks with that strangely evolved language.

I think what you mean with template inheritance is best expressed as dynamic file inclusion in PHP, as simple as

<? require $content ?>
Farceuse answered 3/6, 2009 at 19:38 Comment(2)
Using this solution is possible because all variables defined in a parent (or "controller") PHP script are available "globally" to all includes, and files included by those includes as well, correct?Michaelson
That is correct, the scope stays the same if you include a file. You can even access $this if you include a file from within a class method.Farceuse
K
0

PHP Template Inheritance seems a good alternative. Below is the description from the website:

Template Inheritance is an extremely useful technique for making reusable HTML layouts for a site. It is much more flexible than alternative techniques, such as “including” common elements of a page (like a header and footer file).

The concept has been around for a while, most notably in the Django template engine. Unlike other libraries, PHP Template Inheritance lets you write everything in straight PHP. There is no need to learn another template language.

See more at: http://phpti.com/

Kef answered 6/1, 2012 at 12:43 Comment(1)
"Phpti.com is for sale"Wickiup
C
0

There is a great component, "Redstart Templating" it supports php templates Inheritance in very strong way and all templates are written in pure html and php plus it is extendable , you can create a new plugins and mush more

you can read more about the project here in http://phpbeat.com/doc/templating

Clachan answered 30/6, 2013 at 23:31 Comment(0)
S
0

A template engine i am working on

(supports php-like syntax and include/template directives and working on template inherittance also)

Supports both PHP, client-side js and nodejs with same format

https://github.com/foo123/Contemplate

Straightaway answered 11/8, 2013 at 7:24 Comment(0)
C
0

Puja is a Django-like template engine for PHP http://www.phpclasses.org/package/8283-PHP-Template-engine-that-compiles-templates-into-PHP.html. It also supports validate template syntax.

Closer answered 7/10, 2013 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.