Template Inheritance

Inheritance brings the concept of Object Oriented Programming to templates, allowing you to define one (or more) base templates that can be extended by child templates. Extending means that the child template can override all or some of the parent named block areas.

Note

When $compile_check is enabled, all files in the inheritance tree are checked for modifications upon each invocation. You may want to disable $compile_check on production servers for this reason.

Note

If you have a subtemplate which is included with {include} and it contains {block} areas it works only if the {include} itself is called from within a surrounding {block}. In the final parent template you may need a dummy {block} for it.

Example 17.6. Template inheritance example

layout.tpl (parent)


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

  

myproject.tpl (child)


{extends file='layout.tpl'}
{block name=head}
  <link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
  <script src="/js/mypage.js"></script>
{/block}


  

mypage.tpl (grandchild)


{extends file='myproject.tpl'}
{block name=title}My Page Title{/block}
{block name=head}
  <link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
  <script src="/js/mypage.js"></script>
{/block}
{block name=body}My HTML Page Body goes here{/block}

  

To render the above use


 $smarty->display('mypage.tpl');

The resulting output is


<html>
<head>
  <title>My Page Title</title>
  <link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
  <script src="/js/mypage.js"></script>
</head>
<body>
My HTML Page Body goes here
</body>
</html>

Example 17.7. Template inheritance by template resource extends:

Instead of using {extends} tags in the template files you can define the inheritance tree in your PHP script by using the extends: resource type.

The code below will return same result as the example above.


<?php
$smarty->display('extends:layout.tpl|myproject.tpl|mypage.tpl'); 
?>

   

See also {block}, {extends} and extends: resource