PDA
Partners

View Full Version : Simple template system


ZYV
January 3rd, 2004, 11:01 AM
Hello,

Imagine you need to write a news script. You are not a sloppy coder so you have to separate the HTML from the PHP. There is a very easy way to write a simple template system.

I assume you have something like this in your "template" folder:

news.tpl

..............
<p>{NEWS_TEXT}<br>
<i>{NEWS_DATE}</i>
</p>
<hr>
..............


Then when you have got the text and date from, let's say mySQL you do the following:


define("TEMPLATE_NEWS", "template/news.tpl");

//............

// Get the template
$tpl_news = my_file_get_contents(TEMPLATE_NEWS);

// Parse the template
$tpl_news = str_replace("{NEWS_TEXT}", $news_text, $tpl_news);
$tpl_news = str_replace("{NEWS_DATE}", $news_date, $tpl_news);

echo $tpl_news;

// The implementation of the file_get_contents() available in PHP 4.3, but
// the latest PHP is not installed everywhere, right?
function my_file_get_contents($filename) {

$fp = fopen ($filename, "rb");
$contents = fread ($fp, filesize ($filename));
fclose ($fp);

return $contents;
}


This can be optimize, e.g. you could write a function parse_template($tpl, $replace) where $replace is an associative array like:


$replace = array(
"{NEWS_TEXT}" => $news_text,
"{NEWS_DATE}" => $news_date,
);


and then make a loop like

foreach ($replace as $key => $value) {
$tpl = str_replace($key, $value, $tpl);
}


But I've said simple, isn't it?

Hope that helps,
Z.

amish_geek
January 14th, 2004, 10:11 PM
Interesting... I havent come across how that is done yet in my 2 years of coding. Then again I never really looked for it. Hmm.. now I'm going to have to try that the next time I re-do a site entirely from scratch!

ZYV
January 15th, 2004, 04:18 AM
Hello,

Glad that helped somebody. But I would like to strees that this system is really handy for some small modules or scripts.

I use that for news scripts, feedback forms etc., but if I need a templating system for the site I use Smarty. You should definitively have a look on its homepage: http://smarty.php.net/ . Deep down it uses the samw principles that my approach, but has a lot of cool extra features.

Dan
January 15th, 2004, 07:22 AM
Interesting, handy to use.. Smarty's okay, but really too bulky for small sites.

I'm still partial for include(); :p

ZYV
January 15th, 2004, 09:41 AM
Hi!

Smarty's okay, but really too bulky for small sites.

Yeah, right... That's why I normally use it on large sites :)

I'm still partial for include();

include() is good, but has many downsides. E.g. you will need to mix up HTML with PHP (instead of using wildcards like {YOUR_THING}), it's insecure and then, your PHP in templates will get corrupted if you'll try to write a simple CMS with WSYWIG editor like HTMLarea...

airnine
January 20th, 2004, 04:03 PM
well guys, I'm big on php and

here is a nice little tip for you all hooked on include();

include_once("somefile.php");

good luck

Airnine

Interactive
January 20th, 2004, 05:50 PM
Pretty simple, but I think that may get a little resource intensive after a while.

I built a template system for several different sites for a client of mine, basically just a nice little class that would cache the templates. Works great and on a somewhat active site (35k page views a day) it had no problems.

AdulteratedJedi
January 20th, 2004, 08:37 PM
Anyone ever stop to realise that PHP is a template engine. thats the way it was made ;)

AJ

ZYV
January 21st, 2004, 09:44 AM
basically just a nice little class that would cache the templates

Well.. That's the next step done in Smarty :) If you want to share your code to give an idea to the beginners then you're welcome :)

Anyone ever stop to realise that PHP is a template engine. ...

"Anyone ever stop to realise that computer is a typewriter? thats the way it was made ;)" That's equavalent to what you've just said...?

Interactive
January 21st, 2004, 09:49 AM
Originally posted by AdulteratedJedi
Anyone ever stop to realise that PHP is a template engine. thats the way it was made ;)

AJ

That was what Rasmus designed it for. Then Zend took over and steered it in the direction we're heading today.

I'll post my class when I get back, at class right now.

AdulteratedJedi
January 21st, 2004, 11:18 AM
"Anyone ever stop to realise that computer is a typewriter? That’s the way it was made ;)" That's equivalent to what you've just said...?

Well no, not really. A computer can be defined as a device that computes, especially a programmable electronic machine that performs high-speed mathematical or logical operations or that assembles, stores, correlates, or otherwise processes information. A Calculator could be a computer... a typewriter could not.

I spend a lot of time over at the Site Point Forums especially in the Advanced PHP forum, and have learnt a great deal. This lesson about template engines being one of them, I will quote some stuff that I have learnt.

To me template engines like Smarty are a complete waste of time. If we had to pay they would be a complete waste of money as well, fortunately these packages are freely available (For the Most Part). These so-called “template engines” do not add any special features to PHP that are not already there, and by using them, dynamic web sites become more complex, a lot slower, and harder to maintain.

What does a template engine enable us to do? It allows us to separate content from business logic by supplying it with a template file. The template file is a normal HTML file, with special symbols (variables) in it instead of traditional content, and with special control structures (or: blocks) to influence the presentation logic.

To use a template file with Smarty you would have to do:

// Business code (index.php)
require_once('Smarty.class.php');
$smarty =& new Smarty();
$smarty->assign('title', 'Smarty Test');
$smarty->assign('name', 'AdulteratedJedi');
$smarty->display('index.tpl');

// Presentation (index.tpl)
<html>
<head>
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
<p>Hello All I’m {name}</p>
</body>
</html>


The following code, is completely equivalent, runs much faster, is much clearer, and doesn't use a third-party template engine at all:


// Business code (index.php)
$title = 'Template Engine Test');
$name = 'AdulteratedJedi');
include('index.tpl');

// Presentation (index.tpl)
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<h1><?= $title ?></h1>
<p>Hello All I’m <?= $name ?></p>
</body>
</html>


A lot of you will probably say: "Yeah, right! This may work for simple examples as these, but for more complicated web sites, template engines are a real asset!" That is not true. The example I gave can easily be extended to larger, complex sites. Why is this possible? Because PHP already is a template engine. Examine all template engines you can think of, and compare their features with those of PHP. PHP has them all. And a lot more.

So why do people think we need a template engine? The answer to that question is very simple: PHP has become too complex. Back in the old days, when PHP4 was just PHP/FI, the language was nothing more than a simple template engine. It had variables and blocks, and that was about it. Now, after a couple of years, PHP has been added to (but nothing was removed!) - it now has classes - and a large function library was written. And the latter is where the problem lies.

Pick any book on PHP from a shelf in your local bookstore, and look how result rows from a MySQL database are printed. (MySQL is of course the DBMS used in those books, which should already give you a clue about how bad the book is.) The mysql_-functions are used all over the place in the presentation layer.

Here, in these forums, we have tought people to not use those mysql_-functions directly, but use a database abstraction layer instead. This makes coding simpler (no need to know all those functions for the various DBMS's) and when they decide to use another DBMS instead of MySQL (and they undoubtedly will at some point), the conversion will be painless. What is the result of those lessons? People no longer use those functions directly, so that's good. On the other hand, they still place their business logic all over the presentation code. That's not so good. Most people don't know what to do about it, until they learn about those yucky template engines. No need to carry on here...

At this point I also like to point out that saying "The layout must be strictly separated from the content" is a moot point. What is the layout? That's the colours, the fonts, the styles and so on. The plain HTML itself is the content. A couple of years ago cascading style sheets were introduced, and using these makes it possible to cleanly separate content from layout. I can change 99% of the layout of any of my sites by just changing the style sheet; there is no need to dive into the HTML. Only if the site needs a major overhaul the HTML must be changed. If your web designer tells you this isn't true, fire him.

Another answer to the question "Why do people think we need a separate template engine?" is the following: the biggest part of the PHP community (and the ASP community, for that matter) knows nothing about software architecture. Most of the PHP programmers don't know what an O(n^2) algorithm is, or who Donald Knuth is, or why a sorting algorithm can never be faster than O(n log n), or how Dijkstra's shortest path algorithm works. If they don't know the answers to these basic questions, how can we expect them to know how the design a software program? I'm not saying the majority of the community consists of a bunch of idiots, because that certainly isn't true. There are lots of bright, intelligent people out there, but they just don't know how to write software, because that isn't in their field of expertise. And can we blame them? Of course not. People who use PHP aren't software developers to begin with.

Here are some questions/remarks you may have had when reading this rant, and answers for them.

Q: If you use variables like '$title', as in your example, all over your code, then the business logic becomes a mess, and there is a possibility of clashes between such variables.
A: Then don't use these (global) variables. With little effort you can set up a simple class (or other structure) that store the values for the page you are creating, allowing you to nicely separate presentation code from the business code.

Q: The 'better' template engines have a cache to make loading of pages much faster. Clean PHP doesn't do this, so the template engine is, in that case, faster!
A: Incorrect. The cache in a template engine is needed to store the parsed template in some other format (Smarty uses PHP for that), which can then be instantly restored. With clean PHP the format is already correct, so there is no need to use a cache. Less and simpler lines code, faster execution.

Q: Instead of using a template engine-specific language, our web designers - who know nothing about programming - are now required to have knowledge of PHP! We can't have that, now can we?
A: Why not? The template engine-specific language is nothing more than a minimal programming language with an ugly syntax. It has variables, conditionals, loops, and maybe even functions. As PHP is a full programming language, it has all of these constructs, and more. But that doesn't mean you require your web designers to know all there is to know about PHP. The set of requirements doesn't change at all. Just the basics will be enough. The added benefit is that if they want to, your web designers can start experimenting with PHP (or other scripting languages) much faster.

Q: You said maintaining a web site generated by some template engine is harder to maintain instead of easier. Why?
A: One reason is that an additional software package is involved. At least one person must be able to work with it. More knowledge is required. Also, not only the web site and PHP must be kept up to date; the template engine itself must be maintained as well. This means more work. Another reason is that the best solution for any problem is always the simplest one. Using a large, complex template engine where PHP itself suffices is not a simple solution. In other words: more work yet again.

A lot of what has been said here was by a very valuable person over at sitepoint (in my opinion) called voostind, and I agree with him 100% reading his posts has taught me a lot. He, like me, uses an Object Orientated approach to solve most programming problems. Without a doubt he is one of the smartest PHP programmers over there, he’s just gotten his Masters Degree in Computer Science, and has been studying software architecture for years. So I think you can all agree he knows what he is talking about.

AJ

ZYV
January 21st, 2004, 01:42 PM
AdulteratedJedi

Although I don't agree with everything, my respect for your speech =)

A computer can be defined as a device that computes

OK, my fault. I should have said "a calulator". I meant that PHP is now much more powerful than just an advanced templating solution and sometimes it's suitable for other employment, e.g. I write some kind of "shell scripts for Windows" in PHP (working in the FAR console, similar to MC on Linux).

And then, you haven't covered another important subject. I use my very simple templating class to make possible the use of WSYWIG editors like htmlarea. You see, if the company is big it can hire a designer/webmaster knowing PHP and stuff to handle everything to be done with the website. But if the company is small and you need to make a website so the secretary who doesn't even know the word "PHP" can modify contents and add news.... you need a CMS. Yes, not a monster like postnuke (a waste of time just like Smarty?), but a simple overlaying templating class, isn't it?

AdulteratedJedi
January 27th, 2004, 08:03 PM
I meant that PHP is now much more powerful than just an advanced templating solution and sometimes it's suitable for other employment


I agree Completely. Any programmer who uses PHP soley as a templating solution, in my opinion, is obviously not a very good one, and is certainly not doing the language justice.

How simple of a class are we talking ?? fancy posting it :) I agree a simple templating class can do the job, i must admit i still have a semi-intermidiate (ie does morte than a simple class) in place on some sites. You may wish to have a look at This post (http://www.sitepoint.com/forums/showpost.php?p=532497&postcount=37) for another solution

I never said templates themselves are useless; I said third-party template engines are useless, which is something quite different. I don't see why people think its easier for a web designer to write '{title|function}' (Smarty) instead of '<?= function$title) ?>' (PHP). Tthe latter is supported better by applications used by web designers, as for example Dreamweaver supports PHP, but not Smarty. There's nothing wrong with templates. On the contrary, using them is probably a good idea. But as PHP is a template engine in itself, why would you need a third party one? I really don't see why it would be easier for someone to learn a specific template engine's language instead of a bit of plain, basic PHP. On a sidenote: I never use the <?= tag myself (most good PHP'ers dont either) it is possible to disable this tag, but find me one ISP running PHP that does that.

At the end of the day it all comes down to personal preference, and what solution is best for you. My point, and many others too, is why should you force your designers to learn the smarty language, rather than learning PHP, even if they just learn the basics .. its still better than making them learn smarty, isnt it ?

AJ