Member Avatar

So I have not found a real answer to this yet. If you know you know what I mean. I need to make nested template for my website so that it remains consistant through out and certain sections change on different pages. How can I do this? Whats the best and most easiet way?

I will have around 100 pages or more..

Recommended Answers

All 21 Replies

Member Avatar

I usually like to make things my self. Hate CMS

Assuming you have a value unique to the page (ie $_GET['id'] or something) I would just put everything into the one template file, then wrap the blocks you want to change in an IF or SWITCH statement, so you can decide which bits to echo out.

To achieve this you can use jquery and ajax.
To make it even more flexible you can use database with php and return in realtime with jquery and ajax.
You should look at jquery live and httprequest

Hope this helps

You should look at jquery live and httprequest

Why use HttpRequest if jQuery has them nicely wrapped for you (get, getJSON etc.)?


$pagedata = array();
$pagedata['title'] = 'Test';
$pagedata['cssfile'] = 'template1.css';


<title><?php echo $pagedata['title'];?></title>
<link type='text/css' rel='stylesheet' href='<?php echo $pagedata['cssfile'];?>'>
<div style='background-color:#ccc;'></div>

Pretty simplistic but it lets you switch between templates rather easy

oh and also functions are good for that, store all pages in a mysql database with columns attached to them however you like to do it, then pass it to a function that writes based on it:


if($pagedata['rightcol'] !== false){
    echo createRightCol($pagedata['rightcol']);


function createRightCol($var){
if($var == 1){
$data = 'this html';
}elseif($var == 2){
$data = 'other html';
return $data;

just depends how you want to do it

Member Avatar

Dam I think asp is way easier. I hope in PHP 6 they add php master pages.

These are the reasons why I LOVE PHP over anything else.. I mean I also like active server language, but I think PHP is more extendsible. PHP can also be a very powerful coding language , if either one or all are used.. framework, templating system, OOP..

The same thing with ASP, php just need a descent templating system.. like what Pritaeas have recommended. I prefer smarty or twig, but dwoo is something I can fall back into.

In smarty you can make one master template, and then just extends it for every pages you want to create.. Besides, it will never complicates with the script updates, because each page has its own php file, you are just assigning them to your template file..

Please allow me write an example. Just because I am getting bored on my current google/youtube API work they want me to overhaul.

I prefer using some of my precious time in promoting and convincing other people why PHP is a good programming language if not excellent? In PHP you can also have a master template .

In my example let us call this main.tpl all of the major css and design aspects of your site must be included here...

          <!-- filename main.tpl -->
          <title>[block name=title][/block]</title>
          <meta name="keywords" content="[block name=meta][/block]"/>
          <div id="mainwrap">
          <div id="leftcol">
          <!-- you can assign your left column content here, by creating a left column block -->
          [block name=leftcontent][/block]
          <div id="maincontent">
          <!-- you can assign your maincontent here, by creating a maincontent block -->
          [block name=maincontent][/block]
          <div id="footer">
          <!-- footer content block -->
          [block name=footercontent][/block]

Then on your php file, you can have like;

   ## filename index.php
   $meta = "meta here "; 
   $title = "Title here"; 
   ## of course you always use a shorter assignment, but the sake of making things much clearer, we have to show a much clearer breakdown of the codes.

   ## all contents can be from anything like database.
   $leftContent = "Left Content";
   $smarty->assign('leftContent', $leftContent);

   ## main content .. again this content can be from anything that you want to assign to your template.
   $main = "Your main content";

   ## footer content..
   $footer = "all footer stuffs here";

   ## send all of the above to template of your choice. Lets call ours as index.tpl

Now our index.tpl, should extend the master template above...

  <!-- filename indes.tpl -->
  [extends file="main.tpl"]

  <!-- just add and fill the blocks as in main.tpl -->

  [block name=title] {$title} [/block]
  [block name=meta]{$meta} [/block]

  <!-- add lef tcontent -->
  [block name=leftcontent] {$leftContent} [/block]

  <!-- add main content -->
  [block name=maincontent] {$maincontent} [/block]

  <!-- add footer content -->

  [block name=footercontent] {$footer} [/block]

  <!-- end of our first template -->

For other pages that you need to create just do the same process.. php ->assign ->display ->extends tpl ->fill in the blocks..

The beauty of smarty and other templating system is that you can give your template files to any designer and they can run with it, they can do anything with it, while your php codes are safe from being messed up. At least it is beneficial to you and the people working for you, because no one will get stressed out , and most importantly no one is going to get fired..

One last word, I must confess PHP has more vulnerabilities compared to other server side scripting. However, with carefull planning and testing, these vulnerabilities can be avoided. Although no one can guarantee that it can be eliminated. Anything in public domain are always subject to some type of vulnerabilities..

Another downside of templating system is the learning curve. Most people including myself might ask, why learn a new language just to run php script? I think the only reason I put myself into learning templating system is that, I give so much importance in learning and I will never get tired of learning anything on a daily basis. I wish I would learn something while asleep. Learing while sleeping ? That would be pretty cool.. :) I mean way way much cooler..

thanks for reading, I hope I am able to give you some interesting insight what php is all about..

commented: Nice. +13
Member Avatar

I use RainTPL in preference to Smarty these days. Most template engines have similar functionality, although twig has (IMO) a more complicated syntax. As mentioned previously, template engines require some time to get to grips with them, but can be extremely powerful.

You could roll your own with multiple or nested include files though. The only thing is it's more difficult to separate your html and php via this method.

Twig gets my vote by far. Having used a lot of different template languages for php it is the first one that really seems to get it right.

The syntax is concise but yet still very verbose. It is fast, but mostly it is extensible. Twig is a pleasure to write extensions for that keep the template language looking neat and tidy. Plus it is part of a major framework (Symfony2 Standard) and that ensures it will receive long-term attention and development.

It looks nice. Thanks for the heads up. Does Twig have output caching like Smarty ? Or just the compiled cache? (out of the box)

When you say output caching you mean caching the final rendered templates or caching the templates themselves?

I have always used twig behind Varnish servers which integrate very well with Symfony2 so I use a lot of ESI's to deal with my caching. Twig by default compiles all of your templates down to native php so that is also a kind of cache that vastly improves performance. I also usually run the twig php extension wherever possible to squeeze more performance out of it.

Apparently I don't get notifications when someone comments on threads I've posted in now... +1 for "upgrading functionality" I guess.

I really like what is being done with composer and packagist they make PEAR feel archaic and remove the dependency on libraries that don't get updated fequently on shared servers because of dependency.

Member Avatar

Thanks for the tip - haven't seen them before. WIll do some research.

@mschoeder: Yes, I meant caching of the final output. The caching (compiled templates) as described seems to match the template_c caching of smarty. After reading some more I still haven't seen how to cache the actual HTML page with twig. It seems to refer to external libs for that, but maybe I've missed something. I did read something about caching headers (pragma, last-modified) and e-tags.

Twig's cache is almost the same as smarty..with the only exemptions of twig is doing it much better, because the cache directory is created automatically, and it can detect any changes made on the template files.

Normally, without cache we can initialize twig environment like this

 ## initialize twig environment without cache
 $twig = new Twig_Environment($loader);

To enabled cache, we can just replace the initialization above with

   ## twig environment initialization cache enabled
   $twig = new Twig_Environment($loader, array(
   'cache'       => 'cache/templates',
   'auto_reload' => true

The cache page of the tpl file will be located the root of the script if cache/templates does not exist.. twig will create them automatically.

Now the beauty of twig is its ability to detect any changes in the template file.. if changes were made after the cache file has been recompiled, the twig will use the auto reload function.

In my example code above, I made auto_reload equal to true. So, pretty much it will be a self serving, whenever it detects changes on template file.

The one I like the most about twig is its ability to do a data dump. In smarty, people normally do this

   $value['one'] = $row['one'];
   ## sometime it should have to be like this (string)$row['one'];
   $value['endOfItems'] = $row['lastRow'];

   $valueOut[] = $value;

   $smarty->assign('valueOut', $valueOut);

While in twig it is a lot shorter and faster I think...

 ## twig approach
   $valueOut[] = $row; 


   ## send the above data to the template
   echo $template->render(array (
   'valueOut' => $valueOut

Php function can be added and be called on the template side on twig, and NOT in smarty.. for example

   ## we can add new function on the controller page (php)
    $twig->addFunction('myNewFunction', new Twig_Function_Function('myNewFunction'));

    function myNewFunction() {
     ## function does its job here.

Depending on what the new function does, it can be use on the template side, something like this.

  ## twig template file using function from controller.
  {{ myNewFunction() }}

Forgot to mention both smarty and twig, supports dot notation... which is pretty.handy..

Thanks for this, one last question. I have a single (compiled) template for many pages. How do I make the distinction? In smarty I can set a cache_id, is there something similar in twig? The template changes maybe once a year, the data for all the pages a little more often.

Hi Pritaes,

I think that would require a little bit of work... people were talking about it, why it has to be cache key instead of a name? This person got some tweaks, but encounter some minor problems.

Twig should work on this limitation. I hope it will be pretty soon.

Meanwhile, the file responsible for writing and loading the cache/template file is the Twig/environment.php. They have an updated and modified version of this file at gitHub. The most updated distribution with fixes is Here.

Moments ago, I ran a simple script with cache enabled, the cache sub-directories and files were arranged this way.

--->of->f1->the actual child template cached file.
--->16->5d->the actual master template cached file.

Template nesting and inheritance in twig is exactly the same as in Smarty, with one exemptions on the grandchild's ability to pick up some of the grandparent's (master template) defined block characteristics.. for example, the master template can have the following blocks. The same thing in smarty master template, all css, js and valid html tags must be included here.

For other people who just stumbled upon this discussion, this is the file where all of the styling and beautification must be focused. Designer can have all of freedom to work on this file. There is nothing to break here really. They can delete or missed-up on the curly and percent symbols all day long, our php script will remain safe in the hands of the developer or programmer.

{# filename master.tpl #}

      {% block headerContent %}
      <!-- header content here -->

      {% endblock headerContent %}

      {% block mainContent %}
      <!-- main content here -->

      {% endblock mainContent %}

      {% block rightContent %}
      <!-- righ column content -->

      {% endblock rightContent %}

      {# let say we want a block unique only to the grandchild template, we can add it like so #}

      {% block uniqContent %}
      <!-- this can have styles and design that can be accessed by the grandChild -->
      {% endblock uniqContent %}

      {% block footer %}
      {% endblock footer %}


I hope people who have not tried templating system up to this point, wil be convince that templating system makes html files sparkly clean. Let us create the child template below..

{# filename index.tpl #}
       {% extends "master.tpl" %}

       {# all comment tags here must be enclosed by curly brackets followed by sharp symbol. just like the ones I am using right now. #}

       {% block headerContent %}
      {# header content below from index.php #}
       {{ headercontent }}

      {% endblock headerContent %}

      {% block mainContent %}
      {# main content below from the index.php #}

      {% endblock mainContent %}

      {% block rightContent %}
      {# right column content #}

      {% endblock rightContent %}

       {% block footer %}
       {{ footer }}
      {% endblock footer %}

      {# end of the index.tpl #}

Twig is strict on the comment tags for the template files, but not on the master template file. As long as the master is not called or assigned by any php file the regular html comment tags is ok. For all defined/assigned templates comments has to be enclosed by curly brackets with sharp symbols.

Now let's do a grandchild template example. This will inherit most of its parent's blocks, but at the same time access the grandparent's uniqueContent block characteristics not used by it's parent.

{# filename grandchild.tpl #}
     {# now we extend the index.tpl above #}

     {% extends index.tpl %}

     {# we want the uniqueContent from the grandparent #}
     {% block uniqContent %}
      {# we must use the twig's parent function #}
      {{ parent () }}
      {# this block will have all of the design characteristics as defined in the grandparent uniqContent block #}
      {% endblock uniqContent %}

Thanks for reading... another proof that php can be very very powerful and highly organized just like any other scripting language. Powerful, fast, and sparkly clean codes is my humble way of describing it.

commented: Much appreciated. +13

I know most of us were pretty much have the same beliefs about PHP being the templating system itself, as what Fabien Fotencier (The father and The mother of Symfony) wrote on his blog. Before the birth of twig, he pretty much have the same reasoning as the majority in PHP coders world. However, he did changed his mind as what he had written here.

Although he pointed out the lack of functionalities of the old smarty and the smarty3, he also aknowledged the importance of smarty .

Smarty is the de-facto PHP standard template engine

I still believe however that smarty may still have some few more tricks left underneath its sleeve. A good example of this is the smarty's iteration functions. Only DWOO and Smarty have this and no other template engine would be able to do it on a template side, except when the switch method is passed from php.

The usefulness of smarty iteration property become extremely important, when a coder wants to insert something in between loops, or in any specific nth part of the iteration. For example, we have 100 items stored in some variable as data. If we want to paginate allowing 20 items per page, but at the same time we want banner ad or different item (not from the same variable where the 100 items where stored) every 4th item, this can be easily done on smarty. Although php alone can do this (NOT as precise as when smarty is used), it is a lot easier to achieve this in smarty and dwoo.

**Warning! **DWOO is no longer maintained.. my last post in DWOO forum was almost two years ago, and the forum registration was halted months after my last post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.