PHP Template Engines? 90
kubed asks: "I've recently learned how to use PHP template engines to separate business logic from presentation. Some argue that template engines make applications easier to maintain and make for cleaner code. Others argue that template engines introduce unnecessary overhead and require too much additional processing power. Do the readers of Slashdot think that it is important to use templates or are they just an extra unnecessary layer? There are dozens of PHP template engines to choose from including Smarty, phplib, and bTemplate. Which template engines do you have experience with and which ones have the best performance?"
Template Engines are good (Score:5, Informative)
At present, I am using Smarty with my php programming and find it to be a very good product. It has a number of features built in to make programming easy and quicker for me. Previously I've used HTML::Template for Perl, and have to say I prefer a templating engine when the application I'm building becomes large enough.
The advantages:
Is there an overhead, probably, but Smarty does a number of things to help bring it down. So far, I find it to be more efficient than a case of not using a template engine.
There are so many advantages to using a template engine, that it will probably outweight some of the disadvantages you will encounter.
I have mixed emotions (Score:3, Interesting)
1) Is the rapid development style worth the processing overhead and system-independence?
2) Are you prepared to take the extra time to make the code clean after said rapid development?
Granted, any language can be misused to create horrible code, but with rapid development with template languages, you have to be careful not to let the ease and simplicity of the language lull you into poor programming. However, you do not need to use extra "stuff" to accomplish this specifically, if you are careful to code your data access modules separate from the presentation logic in the first place, which is just good programming style in general.
Re:I have mixed emotions (Score:3, Insightful)
In my experience, bad programming starts with the developer, not with the language. Languages that are more difficult to code in simply make the barrier to understanding a little higher, so they're *more likely* to be used by someone with good programming skills.
Remember: The main goal of
not ready for use yet, but worth looking (Score:1, Informative)
Smarty, Smarty, Smarty (Score:5, Interesting)
Smarty -- highly recommended!
Re:Smarty, Smarty, Smarty (Score:1)
I like template engines (Score:5, Interesting)
Re:I like template engines (Score:3, Informative)
It's powerful, extensible, and - best of all - language-agnostic. I've built several sites using the PHP+MySQL->XML->HTML route and I can't say I've found anything that works better.
Re:I like template engines (Score:2, Informative)
Re:I like template engines (Score:2)
they rock (Score:5, Interesting)
On the positive side, it really helps separate code from display, which makes everything look neater -- as in clean, not as in "gee whiz". HTML is easier to read and it's easier to abstract everything. I'm sure you know the arguments for it already. If you need to change something, all you do is find the template and you can see everything in one clear shot, instead of digging through mountains of PHP logic.
Additionally, if you use a good template engine, it will make your pages load faster by using a caching system. Basically, if your page doesn't change very often, it will save a static copy of all of your PHP logic and return that to the browser instead of making the database calls and other operations that eat up processing speed. I did notice a difference when I wrote my site.
However! There are some important things to remember. Unless you cache your site, it will probably not be any faster. Smarty is, in my opinion, bloated and slow. It tries to do too much and takes forever to load and use. (By forever, I mean like 0.1 seconds to load a page created by Smarty versus 0.005 seconds to load the equivalent page from pure PHP.)
Moreover, websites made with templates are summarily locked into that template engine and new developers will have difficulty figuring out what the heck you did without a good bit of explanation.
One more point to consider is the fact that when using template engines, usually you're limited in the tricks you can pull on your website. Template engines seriously restrict your ability to do cool things with PHP in the display process.
Finally, template engines introduce new flaws into your website. Sometimes those flaws are really bad and affect the performance of your site and then the developers are sometimes difficult to work with and then you have this piece of code that you didn't write that you have to work around.
Those are just things to consider.
Re:they rock (Score:1)
Re:they rock (Score:1)
I have read more comments like this than I can remember, and it is only partially true.
Smarty converts the template to pure PHP code the first time it is
Not terribly useful (Score:1, Insightful)
I use XHTML 1.0 Strict and CSS extensively, so when it comes down to it, there is very little in the way of markup to abstract away, and a template engine merely gets in the way.
If you are constantly tripping over nested tables and font elements, perhaps you are solving the wrong problem by trying to rationalise that markup instead of using HTML properly in the first place.
Re:Not terribly useful (Score:2)
Re:Not terribly useful (Score:3, Informative)
1. Write plain XHTML 1.0 Strict using appropriate markup.
2. Write a stylesheet to get the layout right. Avoid the bits that Internet Explorer fucks up, mostly CSS tables and certain types of selector.
3. Develop against the highest-quality CSS implementation available, usually the most recent Gecko-based browser.
4. Test in other decent quality browsers (Opera, Safari, Konqueror). Include bug workarounds where necessary.
5. Test in Internet Explorer 6.0, i
Re:Not terribly useful (Score:4, Insightful)
For example, a template engine is used in phpBB [phpbb.com] (as with many message board systems). There's a lot of very dynamic and conditional content on message boards, and I honestly can't see how XHTML and CSS can effectively handle it.
By abstracting the markup from the data, you can also simplify the markup. For example, if you are generating a table with an unknown number of rows, you can define a single row in your template and the engine will duplicate it as required. Same thing if you even have multiple tables of multiple rows.
Personally, I think phpBB's engine is a little overboard, but it's like that to be more flexible than the boards I maintain require. For example, I don't see the need to a separate language file for anything I do (although I understand it's usefulness). Similarly, I don't really care for the style table it generates in code from the database (although this makes changing the styles easier via web interface). So to save overhead I remove these features and just put the data directly into the templates.
What I'm really getting at is: Use the right tool for the job. PHP Template engines are a Good Thing(tm) but definately not the Only Thing(tm)
=Smidge=
Re:Not terribly useful (Score:1)
You definately have a point. If your entire site (or significant section of your site) contains tabular data (such as a forum) then you obviously should consider a templating system.
However, the parent also has a very good point. When your markup looks like this:
Re: (Score:2)
My experiences (Score:3, Informative)
Damien
Useful for applying PHP to a non-php enviroment (Score:2)
I've worked in enviroments that require plain HTML, so I was looking at setting up the logic in PHP and using the template to build it out into a static site. The only problem is that I'm lazy and ignorant ; ) and the thought of learning something on top of the PHP, which I dodn't know too well to begin with, was daunting. Smarty seems to be the most mature platform, but it looks like it requires a fair amount of arcane expertise
Re:Useful for applying PHP to a non-php enviroment (Score:1)
Smarty is dead simple, go to the documentation page and start working your way through the table of contents. if you don't have a firm grasp of it by section III give up you're not gonna.
Re:Useful for applying PHP to a non-php enviroment (Score:2)
"RTFM"
Is that how you learned to suck on your mom's dick?
Re:Useful for applying PHP to a non-php enviroment (Score:1)
whining about the rather thorough documentation and making crass comments about my mother aren't going to get you anywhere.
Beyond the Template Engine (Score:5, Informative)
http://www.sitepoint.com/article/1218/ [sitepoint.com]
About (in the opinion of the article author) the superiority of smarty.
Introduction of the article :
TAL (Score:5, Informative)
There's no single answer. Like anything else, it depends on your application.
Templating gives you the flexibility of being able to change the look of the pages independently of the information it represents. Templating requires more planning and design, since it's part of a feedback loop that affects how the information is shaped.
For some applications, separating the presentation logic from the application logic is simply a necessity, and the pains taken to design around a template system is an investment from which you will reap the benefits later, either when you change the application logic or the presentation logic.
(Separation of application interfaces from application logic is usually equally important, not the least because it allows refactoring, ie. the continuously improvement of code without affecting interface compatibility.)
I don't know any of them, as I don't use PHP unless forced to, so no comment on that. However, I have used a lot of template systems in my time, and the best one I have had the pleasure of working with so far is TAL [zope.org].
TAL (Template Attribute Language) was originally implemented for Zope [zope.org]. It is, however, completely general, and has been enthusiastically received by the open source community, spawning several implementations [zope.org], including an implementation for PHP [sourceforge.net].
One of the core ideas of TAL is that it's valid XML, and therefore valid XHTML, and it's designed in a way to does not intrude on the original markup. You can view a TAL template in a WYSIWYG editor like Dreamweaver, and it will look fine; moreover, if the template is well-written, it may even look like a static preview of the real, dynamically generated template.
TAL is in fact just one part of a trinity that also includes TALES [zope.org] (TAL Expression Syntax) and METAL [zope.org] (Macro Extensions for TAL).
TAL specifies the template structure. TALES is a way to refer to external information. And METAL lets you define template regions that acts as reusable macros: headers, copyrights, headlines, boxes, what have you. METAL greatly aids in supporting the idea of "skinning". Represent documents as TAL templates that refer to METAL macros, and to switch your "skin", just point them to a different set of macros.
TAL, which is based on XML, is a declarative language. It will take some time -- but not much -- to get used to. For example, to iterate over a list/array/whatever:
This goes over the elements in the "results" list, and for each element, assigns the value to the variable "person".
Here, we use tal:content to insert the person's details into the table cells. As you can see, TAL uses a path syntax: person/name means the attribute "name" of the variable "person
Re:TAL (Score:1)
Re:TAL (Score:2)
Specifically, XSLT is traditionally applied to static documents. You could apply it to dynamic documents, but how do you generate the document? Not with XSLT. You could generate it with TAL, though, and use XSLT for the presentational transformation.
Re:TAL (Score:2)
METAL has its weaknesses (the worst of which is that macros aren't parameterizable), though, leading to some awkward code; I will grant you that.
Can't see how you can blame TAL for your woes, though.
Template Engines are bad (Score:4, Interesting)
I keep a list of the classes/ids of the divs. I heavily organize the code so that every element can easily be referred to by a class or id according to a heavily commented list of selectors.
The PHP file is all structure/programming logic. I put all content in some sort of database.
Then I write cascading style sheets. You'd be amazed at how many different ways you can make the page look. And not just different colors/font sizes; you can make a sidebar float left or right, or be across the top; you can make links' subsections unfold, or stay invisible until you're in that section; in short, you can make the page be layed-out however you want.
(A few caveats: I've found, in making the css cross-browser compatible, that sometimes you need to do a few work-arounds that pollute the structured PHP document, things like: make a extra div around a div; maybe use a conditional statement to show an INPUT or a BUTTON tag. But you usually need to pollute your non-css HTML anyway if you want to do some sort of tricky design that is cross-browser compatibile and that degrades gracefully.)
For me, a separate PHP template engine means that the template itself will be polluted: you'll have HTML that's trying to do design, instead of just describing the page's structure. And of course, the template page will need some programming logic like loops and conditionals.
Better for your designers learn css than make them deal with some half-assed half-HTML, half-PHP template.
1) With PHP templates
--
* programming logic in php files
* content in a database
* structure/design in template
2) With no templates but using css
--
* programming logic & document structure in PHP files
* content in database
* design in css
Two is cleaner, no?
Re:Template Engines are bad (Score:2)
You change the stylesheet. CSS is not trivial. You can control things BETTER than if you change HTML with formatting.
>what happens when you want to add non-html support
If you are using a template system, you could just change the template. With my system, you'd need to change the PHP. BUT, with my system, you could just make alternate stylesheets to make the page good for PDAs or for print, etc.
Also, my system could arguably be p
Re:Template Engines are bad (Score:2)
Why not do both? PHP templates for the structure, CSS for the presentation. Nothing about templates says that you have to do the styling in them.
Re:Template Engines are bad (Score:3, Informative)
And even with CSS, you o
Re:Template Engines are bad (Score:4, Insightful)
No, not really. I mean, from which end? Your .php files sure aren't going to be cleaner.
Frankly, I think you're missing the point. CSS and templating are not mutually exclusive. Just as CSS helps us separate style from content, so does templating help us remove content from application logic.
3) With templates and CSS
I prefer #3.
Time to whore myself: HTML::Template for PHP (Score:4, Informative)
You can get it at http://www.robotholocaust.com/scripts/template.ph
It uses the same Templating syntax and tries to be a close as possible in API as the perl version, but it doesn't handle caching at all. That's coming soon.
Re:Time to whore myself: HTML::Template for PHP (Score:2, Informative)
Re:Time to whore myself: HTML::Template for PHP (Score:1)
Why don't you work together with the htmltmpl folks?
Just a rule set? (Score:4, Insightful)
Given the apparent popularity of templating systems for PHP I'm likely in a minority, but I really don't see the point. Languages like perl need some way of getting variables and at least some basic controls structures into the HTML so you don't have to resort to multiple print statements (god, the bad old days...). But PHP does this all on it's own already.
Granted, this is often horribly, horribly abused with all kinds of spaghetti code strewn about the presentation layer, but this is the developer's fault, not that of the language. There's absolutely no reason you can't implement an MVC architecture (or just put your main code somewhere other than your presentation layer) without resorting to a templating engine.
As far as I can tell, the only benefit of PHP templates is that it forces you to keep your code somewhere other than in the presentation. This is offset by generally having the ability to drop out into PHP anywhere you want to in the template anyway. In exchange, you add another layer of complexity to your application, increase execution time, are forced to learn a new syntax and are (frequently) shoehorned into the way the template engine thinks you should structure things.
It's also often mentioned that it's easier on non-coders if you're handing the templates off to someone else for markup. But I really don't understand why (excuse the lack of indintenting - slashdot didn't like it)
is considered more intuitive than:And if you're going to expose your HTML people to a tiny bit of code, it might as well be the actual language, which they may find useful someday. (Yeah, there's a couple more lines in the PHP example to suit my own formatting tastes).
It seems to me that their only real purpose is to help enforce some kind of coding standards. I prefer to excercise a little discipline on my own. Nothing but variable expansion and control structures go into the presentation layer. The code that does the real work is elsewhere. If I'm overseeing others, I make sure they do the same. And god help them if they use a print statement for anything besides debugging.
(Caching comes up as an advantage on occasion, but there are other options that don't involve marrying yourself to a template engine).
I'll grant that I might be missing something obvious and wonderful. If I am, this is the place it'll be pointed out...
Re:Just a rule set? (Score:2)
I've thought of this as well, why go to something else that will emulate a language, when you can use the language itself.
I think part of the reason why people don't see the point is that we automatically think of using a template engine first, when we do think of one, and just accept the inherent design of one. I believe current engines are emulating previous ones, and therefore have carried over what they have learned from the old ones into the newer ones used to
PHP is ITSELF a templating language (Score:3, Interesting)
Can anybody explain what any of these templating engines gives you that can't be found in PHP natively?
Re:PHP is ITSELF a templating language (Score:2)
I cannot speak to most of the template engines being discussed; but, as far as fastTemplates goes, here's the difference I see:
fastTemplates is just another PHP class that is prewritten to handle the concept of templates. The chief advantage I've seen in using it is that you can write pure HTML (or for that matter a non-programming designer type can) and then you place tags (formatted like {TAG}) where
Re:PHP is ITSELF a templating language (Score:2)
Your designer has to know about variable $foo, for one thing.
Sounds like a lot of trouble compared with a simple echo statement.
I guess that depends on the scale of your project. If you're doing something really big, or even moderately big, seperating presentation from business logic is a really big deal.
If you are referring to my other post where I said that CSS dramatically reduced the need for template engines, then you completel
Re:PHP is ITSELF a templating language (Score:2)
What am I missing here?
Re:PHP is ITSELF a templating language (Score:2)
In my experience, templating systems in PHP are just classes that are already written to save you the trouble of writing them yourself. Templating is really a matter of creating an object of that class at the beginning of handling a request and then handing the object the elements that you want presented as your program naturally flows. When you're done executing, you tell the object to print itself. This way, your code doesn't need to be aware of the HTML.
Re:PHP is ITSELF a templating language (Score:1)
That description applies to PHP itself, except that the tags are formatted like <?php ... ?>.
Seems to be that the template engines are a just simplified/dumbed down (pick your bias) version of the same idea.
I don't see much use for them; I keep my application and database logi
This has been discussed in detail already (Score:3, Interesting)
Check out the SitePoint forums for Advanced PHP. The pro's and con's of template engines have been discussed over there in length and it is just a great resource for advanced PHP topics. SitePoint Forums [sitepoint.com].
Also, take a look at Harry Fuecks website PhpPatterns [phppatterns.com]. He also has detailed information about PHP templating and the theory behind the code.
My Two Penneth (Score:2)
It does make a lot of sense if you are doing sites that require
theme engine versus template engine (Score:2)
You know what I think... (Score:1)
I think there are way too many business types on Slashdot who spout buzzwords like "business logic" and "n-tier model". Where are all the old-school hacker guys? All I read about these days is making robust code that has lots of maintainability and other boring stuff like that... Is hacking dirty? Only if you do it right :)
Heh, flamesuit on :)
Tried Smarty, switched back to raw PHP (Score:1, Informative)
Then, reality set in..Smarty requires special directories set up to save its cache files,
Re:Tried Smarty, switched back to raw PHP (Score:3, Informative)
You didn't look very hard. check out the "year_empty", "day_empty", and "month_empty" options here [php.net].
Chances are that what you are doing is hardly presentation logic. And if it was.
Re:Tried Smarty, switched back to raw PHP (Score:1)
I also use smarty on a daily basis, and I think the grandparent's post is terribly misleading.
His rant reminds me of people that claim the Atkins diet doesn't work. 9 times out of 10, they are woefully misinformed, underinformed, or just malicious.
This guy should've asked around on how to do things instead of just assuming that if it wasn't immediately obvious, it wasn't possible.
Re:Tried Smarty, switched back to raw PHP (Score:2)
Your original quote was:
Maybe you meant "couldn't" but you said "can't." So I replied with that in mind.
They are the key to programming success. (Score:3, Interesting)
My main purpose is to design interactive applications or "admin sites". I have code templates (seperate from the layout templates). That enable me to generate an decent looking application, with the ability to add/update/delete/browse/copy/update multiple records based on a mysql table in under an hour. I have code that builds a config file based on the database schema, and provides basic data validation for things like phone numbers, credit cards, date ranges, zip codes, etc. So when customers approach me with custom application requests 85-90% of the coding is done.
A side benifit for this is the business logic can be seperated from the infra-structure and templating logic, so the site are easily maintainable (and upgradable, since my template handler scripts, can be swappped out and upgraded). This also helps security, because I will disable certian handlers, based on the authenication level, and can store the handler scritps outside the web directory tree, so if you don't have the proper rights the file handler simply does not exist, or a lesser version of it does.
Another important benifit is that this extra layer of seperation, and pre-coded templates help me maintain a very consistent look across the various admin screen with very little effort (the html forms are automatically generated based on the DB schema, and the user defined config file). That way if you add a field to the database, it instantly appears in your application, no need to update HTML/PHP code, its all done automatically.
The vast majority of the core application is written and maintained by me. I distribute it to my clients under the GPL, but I have not formally released the application other than to people who are using it.
They can be slow, and cumbersome if they are too database dependent, but because the logic and data and layout are all well organized it is very easy to automatically create static pages if need be. (This is another feature of my toolset, albeit an incomplete one).
Anyway, without the structure of a templating system I would not be able to stay in business. I don't believe in plugging my business on slashdot. But, if you are really interested in knowing more you should be able to track me down via my slashdot info. Ask for Brandon
-MS2k
"The HTML template class" (Score:1)
It is basicly nothing else than using php control structures,
but it keeps my html code clean (if you can call html clean).
Its not at all bloated and suits my need for page load.
I'd say its worth a try :)
Just curious (Score:3, Interesting)
You'll like this. (Score:2)
I learned PHP to a moderate level, and now ASP.net to a moderate level, and ASP.net is the first language I have ever felt is truly for the web.
It's not perfect, no. And yes it's Microsoft. But C# is an open spec don't you know. And if MS was ever going to redeem itself, it had to start somewhere. ASP.net on the web is part of that
View on Smarty (Score:3, Informative)
Overhead
As for the argument about overhead, sure all templating engines do add some amount of overhead, but depending on your server load, power of webservers, etc., the significance of the load may either be infintesimal or enormous. I know that Smarty tries to reduce the load by caching the compiled template files to save some time. Basically, on the first page load, Smarty compiles and caches all the smarty files into PHP files, so in the end, you're basically running a bunch of PHP code.
Of course, with all business->presentation, there is the overhead of looping through your data set twice: once to retrieve and store the data, and once to display it. However, this is only a constant factor in complexity, so it should not be a significant overhead.
Flexibility
Smarty is an extremeley flexible templating language, since you can basically wrap any php function and pass it in as a plugin, thus opening up the entire PHP library through smarty functions. In fact, you can always cheat with Smarty and throw in the {php}{/php} tags, though may add confusion to the design process.
And this brings up the largest problems with Smarty though (from a PHP programmers perspective), is that you do have to spend time learning a new language. While several of the constructs are similar to PHP, it is different enough to warrant some amounts of frustration. I'm sure this applies to any templating engine as well.
Alternative to templating "engines"
Like another poster pointed out [slashdot.org], you don't really need a separate templating "engine" to use templates. Templating can be acheived using pure PHP itself, as long as you create the correct classes and strictly enforce keeping all design out of the business logic. (The link gives more details about that).
Smarty may be a good choice however, if the designers of the company does not have PHP knowledge. Teaching them the small amount of Smarty (the language is very small) may be faster than ramping them up on a PHP template. And Smarty was made for this purpose, a templating language with a SIMPLER function set than PHP. It was created (afiak) keeping in mind that not all those HTML/WYSIWYG designers have expert knowledge of PHP.
HTML_Template_IT and templating in general (Score:2)
After a couple of years now, I must say that I *hate* HTML_Template_IT, on a number of levels. Debugging problems is the crap because it fails silently for the most part and I'm left do a lot of manual tracing. Furthermore, it doesn't behave the way I think it should a lot of time, doin
PEAR::HTML_Template_Sigma (Score:1)
I've written a few... (Score:2)
Anyway, it's simple, compiles templates to php, and generates fairly nice code. If Smarty's a bit heavyweight for you, it might be worth a look.
Rasmus Says: PHP (Score:2)
The Template View (Score:2, Interesting)
The notion of templating in PHP (or any web platform) is described by Martin Fowler [martinfowler.com] in Patterns of Enterprise Application Architecture [martinfowler.com] as the Template View.
Implementation of the Template View is examined in some detail at http://wact.sf.net/index.php/TemplateView [sf.net], which begins looking at "Why use templates" then examines different styles of templating, in terms of their markup and the API they provide to populate the template with data. The purpose is to lay this discussion to rest once and for all.
Where
My choice is Smarty (Score:1)
Am I slow? (Score:2)
Due to the nature of the web I have yet to see even a single page were I wanted to force data out before processing was complete. I understand the idea of sending data to the client before it is complete
I wrote my own (Score:2)
with simple @keword substitution
as for performance hit : zero, nada, zip
Because I cache the output of my pages and the forms I use for editing the database entries clears the cache as necessary so I can write my php as un-optimized as I like which places the optimium time saving where it counts - developer time.
I dislike them (Score:1)
Once you realise that a) suitably complex templates will require some form of presentation logic and b) implementing said logic in a template language is completely unneccesary overhead.
The only exception i will make to this is phptal (http://phptal.sourceforge.net) , which is a php implementation of zope page templates.
All tal templates are 100% well formed x
templating in php... (Score:2)
php's built-in template engine (Score:1)
example in use...
/* define the functions args... then for each loop in the function define an outer and inner format string */
function something($arg, $outer1, $inner1) {
for ($i=0; $i<10; $i++) {
$innerLoop
}
return sprintf($outer1, $innerLoop);
}
echo something('cheese', '<ul>%1$s</ul>', '<li class=%2$d>%1$s</li>');
Now you can put whatever you want for the format strings... and the html
Try changing someone else's Templates! (Score:1)
I found that because one template will use another template which will use another template and so on, that the resulting html might have been taken from up to 20 different template files. I found myself s
Re:Try changing someone else's Templates! (Score:1)
There are some really amazing x-cart sites out there btw.
The Way of Smarty (Score:1)
First, a templating engine enforces a set of rules that makes it easier to separate your business and presentation logic because you think of your PHP as code and your templates as presentation. Secondly, the level of reusability goes way up with a
Double your file changes, baby... (Score:1)
The guys (above) questioning whether PHP needs a separate templating engine are right on the money.
Like every man and his dog, I wrote my own a year or two back (I think half the appeal of templates comes from the fun they are to write, which then raises the problem of finding a use for them), and I've used Smarty (for a project which was using Xoops), plus a few of the smaller systems.
In my view simple PHP is (1) just as fast and easy to maintain, (2) more flexible by far, (3) a more portable skill tha
Custom answers (Score:2)
Depending on the logic the templating engine understands, you can make excellent websites with tight HTML in minutes.
The overheads are always present, but it's easy enough to write your own caching methods should