Markup Separation with Template IT

One of the more challenging things I’ve run into while doing PHP development is effectively separating presentation from program logic. In many projects, I felt I was doing a great job until I had to do a markup change and jump through a lot hurdles to make it happen. In my recent projects, I’ve starting using the HTML Template IT extension in PEAR, and its made things a lot easier.

The HTML Template IT extension provides a solid template system that allows complete separation of code and presentation. Rather than placing markup in your PHP files, the markup is contained within separate template files. Within the markup of these templates are variables that can be replaced by dynamic data when the template is parsed.

It’s easy to identify the replacement variables and the file is simple for a designer to edit. As long as the references are there, they will be replaced when the template is parsed. The main goal here is to provide a method for changing the HTML markup without affecting the site’s functionality.

Below is an example of a basic template:

<!-- BEGIN Article -->
<div>
	<h2>{ArticleTitle}</h2>
	<small>{ArticleAuthor}</small>
	<p>{ArticleBody}</p>
</div>
<!-- END Article -->

So, now that you have a template file, you will need to use the Template IT extension to parse it. If you have your own server, you will have to install it using PEAR. If you are on a hosted system, it’s likely that this and other common PEAR extensions are already installed.

Once installed, the extension is easy to use. There are 3 steps to the process: load the template, set the replacement variables and parse the template. Here’s an example of how to parse the template from the example above:


<?php
	require_once "HTML/Template/IT.php"; //Require the extension
	//Instantiate a template object and set the template directory
	$tpl = new HTML_Template_IT("templates");
	//Load the template file
	//the boolean values tell the parser to remove empty or unknown items
	$tpl->loadTemplateFile("article.tpl", true, true);
	//Provide data for the replacement variables
	$tpl->setVariable("ArticleTitle",$title);
	$tpl->setVariable("ArticleAuthor",$author);
	$tpl->setVariable("ArticleBody",$body);
	//Parse template and print
	$tpl->show();
?>

The example above is very basic, but the template system provides a lot of flexibility to do more. Using the BEGIN and END commented HTML in the template allows multiple blocks to be defined in one file. You can even have nested templates. For example, if your template contains a select list, you can make the options template blocks nested within the template. This option block could be parsed as many times as necessary, then the containing block can be parsed. This leaves you with a completed page and allows individual portions to be repeated as many times as necessary.

There is also another option for parsing the template. In addition to the show method, there is also a get method that returns the parsed template in a string rather than printing it. You can easily use this to insert one template into the replacement variable of another template. This allows you to use one template to contain navigation, headers and footers, and insert a parsed template into it as content. Designers can then make global changes to a master template file without affect individual page content.

There are several other template systems available for PHP both through PEAR and other sources. Template IT is one of the simplest systems and easy to get into, but doesn’t provide as much functionality as some of the other systems. If you like the idea of templates, but need a few more options, check out Smarty or Flexy. Whether you’re developer working with designers or doing it all your own, using templates will make maintaining your code much easier.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • sc

    Savant remains my favorite templating system.

  • http://www.lopsica.com BerislavLopac

    It is nonsense to use any templating system apart from the PHP itself, as anything else is just reinventing the wheel. Instead of reiterating the arguments all over again, I’ll just point to this classic article.

  • http://ian.sundermedia.com Ian Muir

    In some ways the article is correct, but it assumes that logic must be inserted into the template.

    The repeating users example that uses a foreach loop can be done with a few HTML comments in Template IT.

  • http://www.phpism.net Maarten Manders

    Create a low-key templating language and people will start complaining about missing features. Then make it a powerful templating language (Smarty, *caugh*) to realize that it’s just PHP with a more screwed up syntax that noone understands.

    As BerislavLopac already stated, PHP itself is a templating language. Stick with it and do it the MVC way. (ZF View is quite elegant)

  • http://www.rideontwo.com z0s0

    Absolutely agree with Berislav & Maarten – having tried both options extensively, native PHP wins for me.

  • http://ian.sundermedia.com Ian Muir

    I guess we have to agree to disagree here. I’ve had pretty good success with templating and some pretty catastrophic failures when allowing designers to play with code. Without fail, one of them will look up some PHP function and throw it into a template without having a clue what they’re doing.

    I’d also point out that the article doesn’t say that templating systems are bad, he just points to the fact that he developed his own system that he prefers and makes more sense to him and his team.

    Templating works better for my team, so that’s what I use. If you have designers that don’t mind learning a little PHP, then maybe it’s not for you.

  • metapundit

    PHP as a templating language? Yes and no. What you lose with PHP embedded in your markup (as opposed to placeholders) is the ability to open your template files in a browser with out running them while you’re tweaking the HTML. For example I use Flexy as my template engine and I can write a complete html file (html, head, relative link to css and javascript) and debug it just in my browser but specify that when loaded as a template only stuff inside the body tag will actually be used (this is the flexy:startchildren directive). Because flexy can embed all it’s looping and conditional constructs in the html tags themselves, the html looks clean in my browser.

    Now it’s true that no template language will ever be complex enough – the solution than is in fact to use PHP for your view code (and be clear – templates do not separate code from presentation: they separate model code from view code). Let’s say I have a template that was being passed an array to generate a UL and now I want to generate a 3 column table. I’ve been down the futile path of adding an ever richer buffet of plugins to the templating language to meet each such special case. The solution is just to allow PHP in your templates, enforce the coding standard of only allowing data munging PHP in the head of the template when necessary and content yourself with a fairly sparse template API.

    One last word though – people should not be encouraged to use old style API’s (PEAR’s IT/Sigma/etc) since it requires so much code to drive them (set the looping context, parse for every loop) that your model and view become tightly bound – changing one requires changing the other. This defeats many of the advantages of using a separate template. Flexy has it’s rough spots but passing all the data to the template and letting it use conditionals and loops is vastly preferable without making the templates any more complicated…

  • http://www.lopsica.com BerislavLopac

    If you have designers that don’t mind learning a little PHP, then maybe it’s not for you.

    Actually, I don’t let designers anywhere near any code, period. A prerequisite for a Web developer is to know PHP and HTML and CSS equally well, so I don’t allow the designers to convert their designs from, say, Photoshop to HTML. It is very rarely to meet a designer who is willing to learn his code well enough, and only occasionally is one person equally skilled in design as with code (like this guy here, who I’m lucky to sometimes work with).

  • http://ian.sundermedia.com Ian Muir

    Again, you’re assuming everybody works like your team does.

    In all honesty, I’ve contracted for 5 different agencies in the area and 2 software vendors and in all cases the markup and CSS was left to the designers. For example, my current team has 3 developers who know PHP and Perl and one designer who has strong HTML and CSS skills.

  • Evert

    We use a template engine as well.. main reason is that we don’t want to give the users the power of PHP..

    Our clients can freely modify the look of the app.. but not the behaviour.

  • Deane Barker

    [...] some pretty catastrophic failures when allowing designers to play with code

    This always confuses me. How big are your shops where you have someone to just sit around to do markup all day? In my company, a “designer” goes no farther than Photoshop. Developers write the HTML and the CSS and do all the programming.

    Are there a lot of shops where you have people who just do the HTML work and no programming? I know this is the ideal that gets thrown around whenever people talk about templating languages, but I’ve never worked anywhere where this was the case.

    As far as choice, I’ve never had to look further than Smarty. We need another PHP templating system like we need another Javascript library, which is to say, like we need a hole in the head.

  • http://ian.sundermedia.com Ian Muir

    My wording was a bit confusing, by code I was referring to PHP. I generally don’t consider HTML markup “code”. We don’t have people that just do markup, the companies I’ve worked with usually have designers that also write markup.

    It seems that I’ve hit on a rather hot button issue here. I was unaware that template systems were so controversial.

  • Anonymous

    > Again, you’re assuming everybody works like your team does.

    i would say that as a web developer you would need to know html, css just as well and just be as proficient with those as you would need to be with the given language you develop with.

    there is no two ways about it really, regardless if you take on the services of a web designer or not; it’s just something you can’t live without really.

    on the point of web designers, in a lot of cases are not too keen to learn the basic syntax of server side languages… it is difficult to find someone who you know well enough to trust them not not make a complete ar*e of things.

    those designers who do know better are few and far between unfortunately. on the point of templating i don’t think there is a need to use something other than php it’s self; sure you need to have foreach() loops etc but that isn’t here nor there.

    the whole goal of separation isn’t about keeping php it’s self out of the template, but it’s about keeping business logic out of the template and nothing more.

    a lot of people don’t make that particular distinction because they are not educated enough to know that there is that particular difference.

    really, i shouldn’t need to make this arguement, surely not in this day and age?

    dr livingston

  • Etnu

    PHP *is* a templating engine. The entire system was written this way from the ground up. If you don’t believe me, look at any one of the dozens of articles and email threads on the php developer’s mailing lists from Rasmus Lerdorf (the inventor of the language).

    The argument that using a templating engine is easier for “designers” is absurd. In practice, “designers” barely know HTML at all, let alone know it well enough to actually be writing the templates for a site or even making small changes. This is the job of the web developer, and the web developer should know PHP.

    I’ve worked for tiny 3-man operations and 15,000+ employee strong internet companies, and the work load separation is always the same:

    - Designers (Visual Designers, Interaction Designers, etc. — people who use adobe tools to show how they want things to look / work)
    - Engineers (Back end, front end, in between — people who use programming languages and other tools to produce actual web pages).

    I’m sure there are some truly weird companies out there who have people who only write HTML, and perhaps there are also a few out there where the engineers never write HTML, but these companies are few and far between (and, quite frankly — backwards and inefficient).

    Sometimes you can toss “Web Developer” in there, and that person is usually an engineer with some familiarity with a designer’s tools.

    HTML and CSS are not intuitive for a visual designer. They weren’t created for visual designers in the first place — they were created by engineers for engineers who wanted a better way to implement the complex designs that the designers were asking for.

    No serious company expects designers to be proficient in html or CSS — it’s nice if they are, but that’s about it. Do a search on any major job board (hot jobs, monster, etc.) for these skills and you’ll notice that in almost every case it’s for a developer position, not that of a designer.

  • http://ian.sundermedia.com Ian Muir

    It seems like one of the big questions that has come up is who writes the HTML and CSS within the typical web team. Rather than drag the comments out here, I’ve made a post over in the forum.

    If you want to continue this discussion, that might be a better place to do it. It’s an interesting topic and it would be interesting to get a wider viewpoint through the forums.

  • titface

    I have worked in 3 differnet design/development companies in the UK and everyone of them had/have people employed for HTML/CSS (and usually javascript) work only.

  • jeff

    You people are cowards not to face up to the power of PHP.

  • http://www.sudokumadness.com/ coffee_ninja

    It’s my opinion Maarten has it right. If you separate responsibilities intelligently (via MVC or some other pattern or paradigm), your view code ought to be dead simple. If you’re doing anything more complicated than iteration, variable output, and some simple conditions, you ought to consider moving that code to the controller.

    At that point it seems a little inane to argue over what template or language syntax is the best.

    Another point in defense of PHP as a template system is that, more often than not, a template system will implement a caching mechanism which translates the template code to PHP, adding yet another level of complexity to your process. Why not just write PHP in the first place?

  • Sven S.

    I’m an advocate of plain PHP-templates, which is why I really can’t see any advantages in Template IT.

    But you’re post inspired me, Ian. I wrote an own article about it in my blog. Feel free to comment here or there:
    Template-Engines for PHP: An age-old (useless?) discussion?

    @coffee ninja:
    I have to agree with you 100%! Caching parsed templates in template-engines is the most useless thing I’ve ever seen. Well, it’s useful for the TEs, but if you really take a look at the big picture one should realize the value of “simple” PHP.

  • http://www.pixelsoul.net pixelsoul

    I too have looked many times at what is the best solution for seperating the html from logic.. tried smarty / pattemplate / xslt and what not.. but after doing allot of reading and testing i too think that php itself is the best templating language. I like the way cakephp handles it.

    But offcourse whatever works for you :)

  • Jason

    I’m sorry but I’ve been working in the “web” industry for almost 8 years professionally, and I have to say that as a “developer”, design and coding to go hand in hand. This may not be an industry standard, but it should be. If you can’t build it how can you be expected to design it. We just hired a new guy ( that didn’t work out ) and the major issue was that he could design but he couldn’t code… so he got the axe. It is my believe that without a knowledge of how sites are built (css, html etc… ) you shouldn’t be designing :)

  • dusoft

    I agree with the above commenters, PHP itself is an exquisite templating system, so there is no reason to invent the wheel over and over again (yes, I am looking at you, Smarty).

  • http://www.lopsica.com BerislavLopac

    When I worked for a small Web dev shop a few years back, we had two designers. Both were quite good in terms of visual talent, but while one was ready and even eager to learn CSS (both used traditional Dreamweaver-generated tag soup beforehand) and adapt his designs to that medium, the other was resolute to never change his design style. So I ordered the latter never to go anywhere near any HTML, and he would just give me the main layout and any prepared graphics, which would I then transform into HTML+CSS. With this approach we kept a great designer while speeding up the process; before that I would spend days getting this guy’s design to a clean state.

  • http://www.saumendra.com Saumendra Swain

    There are many Flavour Of Templating System out there. And the basic need of time is how to implement them. Weather its Smarty , Flexi or Template IT or the native PHP templating System, the value out of these comes from its accessibility and ease of use. So The Crux out of all the discussion going here is that Whatever flavour anyone uses it must be a mello-gello for his lips.

  • Jeremy Coates

    There’s also PHP XTemplate which uses similar markup to that shown but also allows for whole arrays to be assigned, the superglobals and defined elements etc. to be automatically available in the template. Blocks can also be iterated over with ease.

    e.g.

    
    include_once('xtemplate.class.php');
    
    // Instantiate the class and pass it the template file name
    $xtpl = new XTemplate('mytemplate.xtpl');
    
    // Fake some database style results
    $myarray = array(
       0 => array('name' => 'apple', 'colour' => 'green or red', 'an' => true),
       1 => array('name' => 'orange', 'colour' => 'orange', 'an' => true),
       2 => array('name' => 'pear', 'colour' => 'green'),
       3 => array('name' => 'banana', 'colour' => 'yellow')
    );
    
    foreach ($myarray as $row) {
    
       // Assign the variable
       $xtpl->assign('fruit', $row);
    
       // Check if we need to change our grammar
       if (isset($row['an']) && $row['an'] == true) {
          $this->parse('main.row.an');
       }
    
       // Parse and reset the row for the next iteration
       $xtpl->parse('main.row');
    }
    
    // Parse and output the template
    $xtpl->parse('main');
    $xtpl->out('main');
    

    And the corresponding template (‘mytemplate.xtpl’):

    
    <-- BEGIN: main -->
    Here is some fruit:<br />
    <-- BEGIN: row -->
    A<-- BEGIN: an -->n<-- END: an --> {fruit.name} is usually {fruit.colour}<br />
    <-- END: row -->
    <-- END: main -->
    

    Should produce the following output:

    Here is some fruit:
    An apple is usually green or red
    An orange is usually orange
    A pear is usually green
    A banana is usually yellow

    (Not that maintaining the project makes me biased in the slightest!)

  • mrclay

    I think what everyone wants is a template language that’s familiar and expressive, but which only provides access to the given data. E.g. no $GLOBALS, $_SERVER, nothing that could trigger errors/halt execution.

    Has anyone thought of a template language based on ECMAscript?

  • mrclay

    To clarify, I was imagining an ECMAscript-based language that would be compiled server-side to native PHP code.

  • jeff

    Are you people still talking about this? I laugh in your face. Move on…

  • subhash garai

    i am having to build a similar type blog
    thats why i am looking at it