Advertisement

Template Inheritance

Template inheritance is an approach to managing templates that resembles object-oriented programming techniques. Instead of the traditional use of {include ...} tags to manage parts of templates, you can inherit the contents of one template to another (like extending a class) and change blocks of content therein (like overriding methods of a class.) This keeps template management minimal and efficient, since each template only contains the differences from the template it extends.

A Use Case Demonstration

The challenge: Let's say we are creating an HTML page, and it requires some custom Javascript/CSS files loaded within the <head></head> of the document. The problem is that this is defined in the header.tpl, which was included further up the page. There are many ways to address this, but they can get quite messy. Let's make this task an easy one, with Template Inheritance, new to Smarty 3.

Before template inheritance, we were stuck with using {include ...} tags to share content such as headers and footers. Here is an example:

output of mypage.tpl

Instead of managing our page layout in several files (header.tpl, footer.tpl, etc.), we now manage it in one
cohesive template (layout.tpl), and define the changeable blocks of content with {block ...} tags.
Now you can simply extend the layout.tpl (which basically copies it) and then customize any of the defined block
elements. You can have any number of child templates chained together, thus the concept of inheritance.

So back to our initial challenge, how do we address the need to have custom Javascripts/CSS loaded in the header?
Simply add a new block to the layout.tpl, and customize it in the child template: