Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm currently having a discussion about the choice between PHP as a template engine versus a template engine on top of PHP.
What is your choice, and why?
I say why use another template engine when PHP is a template engine itself.
For template engines:
Added security for end-user customization. Themes in pure PHP have unconstrained ability to cause harm to a user and their installation. Thus a template engine removes that risk, if it is a good one.
Ease of use for non-programmers, such as graphic artists or web designers.
For plain-php:
The speed of pure PHP cannot be matched by any template engine built atop it.
The full power of PHP is available to the output, and not just an interpreted or filtered portion.
I prefer PHP itself if at all possible. And most folks don't want to hack your software by making a custom theme, so it's easy to take a cursory read and investigate its security. That said, I am the "between guy" who does both templating and programming, and even some graphic arts; my skillset differs from a strict programmer and a strict artist/designer.
I found that when I introduced Smarty, it was fairly straight forward to get web designers to produce HTML with smarty variables. The folks on the programming team now concentrate on more back-end work, that is, the production of the content of the Smarty variables.
This has shortened the development lifecycle, with work being able to be split between more people, and has ultimately led to better designs.
Well, it's just my opinion, but template engines suck. You have to first understand how the template engine is implemented and then learn how to use it. It seems just wasted time, because PHP alone does it best and offers much more flexibility.
The following reasons apply:
Separating your application into templates with an engine makes your application less vulnerable to halting code errors
Using templates can give you greater flexibility in the future when refactoring because the namespace won't be directly built into the application
Using templates encourages (forces) developers to keep business logic and code OUT of the presentation layer.
Using templates it is easier to mock up datasets and pass them to a template engine and get a preview of what the site will look like with data
PHP is not a template engine, but a language that can be used to write templates, or template engines. A template engine is not just a language, but also the programming API that allows the scripts to locate, organize templates or assign the data from the script to them. Pure PHP offers you absolutely nothing - it is just a language. Instead, you should take such libraries, as Zend_View in Zend Framework to comparisons (basically, it works exactly in the same way, as Smarty, except that it uses PHP to write templates). You should ask whether you should use a template engine with PHP or something else as a template language.
When it comes to templating languages themselves, then well... ordinary loops and conditions are enough to write templates, but this "enough" does not mean that it is easy, comfortable, efficient or flexible. PHP does not offer anything special for template designers, but many "templating languages" (like Smarty) provide just a limited subset of PHP, so I'm not surprised that programmers choose PHP. At least they can write functions and use OOP which is too massive for this (in my opinion), but does work and really helps.
The point is that custom templating languages are not limited with PHP drawbacks, but their designers unsually do not see it, claiming that "displaying variables and a loop is enough". The possible areas, where templating languages could be much more effective:
Form displaying and rendering (I haven't seen any framework with PHP as a templating language that provided an easy, flexible and generic system for customizing the form look).
Understanding the HTML/XML document structure.
Automatic XSS injection filters.
Solving various common problems in the presentation layer (i.e. customizing the look of the pagination system, displaying the data in columns etc.)
Template portability and true separation of the application logic and implementation details from the templates.
Examples of templating languages that follow this way are mentioned above PHPTAL and Open Power Template 2. Some similar ideas can be also found in TinyButStrong, but unfortunately this template engine is extremely slow.
Using a template engine can be helpful if you have a non-programmer doing the templates. In many cases, the simplified template language can be easier for a non-programmer to pick up than PHP itself.
That said, I find myself moving away from using templates when it's just me (or me and other developers).
PHP as template engine will not complain when you mix up your HTML syntax. It will let you forget to close tags, mis-nest them, etc.
PHP's output is not escaped by default, so unless you remember to rigorously add htmlspecialchars() everywhere, your site will have HTML injection (XSS) vulnerabilities.
<p>Hello <?= $name ?></b>
<!-- Simple template full of errors -->
These problems are much worse when you try to generate XHTML properly. It's not that you can't do that with plain PHP - of course you can - but that requires more effort and diligence.
That's why my recommendation is PHPTAL. OPT2 is OK too.
Savant is what you are looking for. Its a nice wrapper class that allows you to use the PHP operators in your templates instead of interpreting an new template language on top of PHP.
Pros:
It makes sense not to add extra work to the system.
No learning curve for developers
If you everyone is disciplined then this is the way to go. (Savant)
Cons:
Although Savant encourages you to separate properly it doesn't force the developer to separate business logic from development code. I have a rule that should never be broken. You can only output variables, use conditions and loops in your templates. You must never allow a developer to create variables in the template. Unfortunately developers never seem to do this no matter how many times you tell them. So, using a engine like Smarty then becomes worth it because the developers are forced to completely keep business and design apart.
If I'm doing a project for myself or one that doesn't have many developers I tend to use Savant. If its a project that is much bigger than just me then in the Architecture I'll go for something like Smarty.
Either way, the separation in the code is important weather you use Savant or Smarty. I'm sure there are other good options out there too.
PHP is perfectly suitable for most tasks, but a templating engine can help a project to scale more easily.
Off the shelf ones like Smarty or PHPTAL are great if you do not have the time to roll your own (and do not require more than they offer). Also, you can fairly easily replace/modify them with your own implementation later on if you find you need something more specialised.
I've personally had a good experience with PHPTAL, primarily because it keeps out of your way and is simple.
I found building a light-weight template engine in PHP worked best for us. Allows for good code separation, and our graphic designer could learn a few simple rules to follow, but most writes HTML/CSS not PHP. I can write the heavy lifting code without having the think much about the interface.
The following article sum-up the different points of view about Template Engines for PHP.
Doing PHP templates of the third kind
http://www.tinybutstrong.com/article_3rd_kind.html
My choice for any new project would probably be to simply use the templating capabilities of PHP, possibly in combination with an MVC framework, instead of using another templating engine. After all, for code simplicity or cleanliness of separation, it doesn't really matter whether you have {$myVar} or <?= $myVar ?> in your code. More complex templating features such as conditions, loops, or backend-technologies such as caching can be handled just as well (or better) by PHP or the MVC framework.
I have used both approaches (with and without a templating engine), but only in personal projects, never in team projects, so perhaps there are compelling arguments for the use of a templating engine in such a setting.
I don't know whether it is due VirtueMart, Joomla or the concept of templates in PHP, but adjusting VirtueMart to your own graphic theme is PURE HELL. (I'm not talking about plain CSS-styling.)
PHP isn't a templating engine its a scripting language.
PHP coding features evolved, designing feature are the same, that's why if you work in a team with designers and developer you need a template engine to parallelize the job, and let the designers work with HTML.
My personal choice is Raintpl, because is lightweight, friendly and fast
here a benchmark can help you choose (also smarty and savant are nice!):
http://www.raintpl.com/PHP-Template-Engines-Speed-Test/
If I had to spend the time learning a standalone template engine, I would rather spend the time learning a Framework instead. My choice is to go with Zend Framework, which when implemented using an MVC approach, provides you with the power of the framework, along with the native templating capability of PHP itself.
Since I asked this question, I have came across mustache. This is a logic-less template language.
So this is not the same as PHP or smarty where you have the possibility to add all sorts of logic to you template, but forces you to keep all the logic in something like view models.
This seems to me a better option then switching to template language where logic is still possible.
I use a template engine in PHP because I prefer to have a high degree of separation between business logic and presentation logic. Web programming is much easier when your PHP (or any other programming language) doesn't have HTML scattered throughout. This is Microsoft's code behind is so popular.
I use a template engine called KudzuPHP. It is a port of my KudzuASP for Classic ASP. It differs from many template engines in that the code that hosts the business rules and logic becomes an event handler for the template engine after the template engine is invoked. This approach allows you to modify the templates (moving large blocks of presentation) without requiring you to modify the code of the PHP code.
KudzuPHP contains it's own library system and writing new extension tags and libraries is very easy.
You can find KudzuPHP here: http://www.andrewfriedl.com/downloads/
If you want a version embedded in a Wordpress plugin that allows you to code against the Wordpress API without PHP go top Wordpress.org and search the plugins for "Kazoo".
currently, it the most faster and easier to use. After making a suite of benchmark on PHP templates engines, twig comes in the second place just after native php language.
I wrote a blog post about this recently.
For the security sake alone, definitely use a templating engine ( Twig is secure ).
A good templating engine (such as Twig) offers:
Security (most important what so ever )
Not verbose (like php)
More templating features
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am building a website in php with lot of pages and we are a team of 9 working on it. So just want to explore that when should we use PHP template engines and when we shouldn't. So I'm interested in pros and cons of using PHP Template engines so I can make a decision whether to use it in my case or not.
PHP is a template language.
In my experience so far with various template systems, the conclusion was pretty simple: use none.
Instead, write PHP as it should be written! Never do anything inside a .html besides echo and for/foreach. If you write the code based on a design pattern like MVC this becomes even more obvious: just echo and foreach inside and explain the frontends they should never mess with the code inside <?php and ?>.
It worked for me ever since. It usually was harder for me to explain them Smarty than to explain to never mess with php.
Template systems also add weight to your server (sometimes is just a bit, sometimes you may feel it). It may seem over-optimization at first, but I prefer to keep it as simple as it can be.
Note:
Smarty, for example, is HARDER to spot in a .html file because the only Smarty syntax highlighter I know is a NetBeans plugin and it's pretty beta. PHP, on the other hand, has it syntax highlighted in any decent editor. Also easier for the frontends to spot and not mess with.
Wrap up
Cons (for using template system)
Increases server load (lighter or heavier, doesn't matter - you can see it)
Induces bad practice (logic wrapped inside template language syntax)
No syntax highlighting for template languages' syntax - harder to spot (for coder and frontend)
Time spent learning it and teaching it to the frontends
Harder to explain to the frontend team (I've taught basic PHP to frontends several times - while many more were already able to write their own 'beginner-level' PHP; I have never taught a frontend Smarty so they can do something other than {$var} )
Makes you avoid the REAL problem: logic and presentation separation!
Adds extra weight to your project
Pros (for using template system)
Extreme boredom (probably the only valid argument)
Template system replacement
Logic and presentation separation (I'd suggest MVC for this task and for the pros it provides for other fields of development: easier maintenance, abstract database and so on)
Force yourself to write in the view only echo and iteration for echoing: foreach and for should accomplish 99% of the iteration needs; you can also use while and do while
For me, when deciding if a separate template engine should be used or to just use PHP for the templating, it always boils down to this:
When to use template engine
When you must restrict (sandbox) the code that can be run in the templates.
When not to use template engine
All the other times.
The PHP purists will tell you that PHP is itself a template engine. I consider myself a purist on this matter, and recommend just using PHP. It even has an alternate syntax for if and loop blocks that are pretty much designed for template-style readability.
Some people, however, still prefer using template engines, such as Smarty. There are a number of things to consider if you do choose that route:
Who's going to be maintaining the template? If the person maintaining the templates already knows PHP, there's no point in making them learn a new, pseudo-PHP template engine. If they don't know PHP, then it's still questionable, depending on their background, since most template engines just implement a syntax not unlike PHP tags (such as <% %>)
How complicated will your templates get? Some template engines are extremely restrictive in what you can do in the templates (forcing you to put everything in the controller, some almost to the point of uselessness or unnecessary hoop-jumping), while others are about as permissive as raw PHP (which many would argue defeats the purpose of a template engine).
How much does efficiency and speed matter? Template engines add overhead. Period. Converting the custom tags to PHP tags takes resources. How much they add and how much it matters depends on a number of factors (including the engine itself). If you need more speed from your site, then I'd vote the template engine as among the first to go.
As I said, I also recommend using PHP as your template "engine," but do be aware of some of the pitfalls. Mainly, it's really easy to add more logic than necessary into your templates. Make sure you have a rule to only include echo, for/foreach, and basic if blocks (such as if is_admin() and the like), and make sure to enforce it.
There is absolutely no reason to use a php template engine.
The seperation of logic and view is a obligation. This does NOT mean using a template engine.
With a template engine you have to learn things that have nothing to do with php or to do with anything else. Each person who have to modify the sources of smarty or an other template could be annoyed about that crap of anything useless and hindering mess.
PHP enpowers your templates an give you all possibilities in each way you use it.
With a dozen of advices PHP ist secure enough. Don't feel secure by using a template engine without knowledge of the tricks behind. Smarty can not secure public editable templates.
Look for Designpatterns. View Helper and MVC. Hold your code simple and well structured is meaning being smarter than smarty/any-template-engine ...
I would suggest using some method of good separation between your display logic and other data fetching maniuplation. Implementing MVC is a great way of doing this and most of the PHP frameworks provide an MVC framework.
This allows everyone to work on much cleaner code and allows the templates to remain simple so that those less technical (front-end designers for example) are able to go in and edit them.
A template engine should be used when there is a great deal of presentation that is duplicated across multiple web pages and you have a desire to separate business and application programming and logic from presentation.
Benefits of this separation are:
tighter, more readable and error free application logic
alter presentation without altering core logic files
altering presentation dynamically at run time
While it is technically true that php is itself a template language it is more accurate to describe it as a web programming language with built in templating. On the other hand it is also true that most template engines consume templates with programming directives built in. This implies that a reasonable balance exists between too much template within php and too much programming within a template. The better the balance the easier your coding and the more flexible and extensible your application will be.
Take for example php code that retrieves your last 10 blog posts and writes them out to a DIV tag on your blog when that code is invoked. If that same code was duplicated to create an RSS feed you would have the same code in two places requiring the need to maintain it in multiple places when the logic changes.
If rather the exact same code is invoked under the control of a template engine then you have the same code writing to two different forms of output based on whether an RSS/XML or HTML template was provided. If the template engine is written well the php code neither knows nor cares what type of template is provided to it. The php could just as well be outputting HTML, XML, SQL, PDF, or text!
Having implemented many websites in Classic ASP and PHP over time I found that a good template engine saved me many long hours of programming and debugging and because there was no real template engine for Classic ASP I wrote KudzuASP to address the problem. You can find the related project KudzuPHP on my website and it is free. There is also a plugin for Wordpress based upon it.
You should always use some mechanism for separating markup from code just like you shouldn't embed CSS in your HTML. There are too many options to give you a flat answer. There are template engines like smarty or fasttemplate, then there are frameworks with templating systems (like cake, code igniter, etc). You should evaluate them individually based on your needs
I would just use php for your template engine. No extra overload from having something like smarty. They just need to know basic php. You can signify the template files with a .phtml file extension...Why would you want to use a templating engine?
Just to be clear, there should only be echos and foreachs inside the .phtml template files, no core code should be done inside of there.
Have you tried Stamp Template Engine?
It still increases server load; however I think it fixes the other cons of template engines. Unlike Smarty and all the other template engines for PHP, StampTE is completely logic-less. You only mark regions with proper HTML comments (most designers and front-end engineers already have these markers just for readability). It relies on these markers to offer cut-and-paste functionality to back-end developers. Back-end PHP programmers can copy-and-paste these regions from the template (like paper models) and construct website and web application GUIs with it. Also, they have a very friendly API themselves. For instance to cut a region like:
<!-- cut:siteMenu -->
<nav>
<ul>
<li>...</li>
</ul>
</nav>
<!-- /cut:siteMenu -->
They can use object oriented notation:
$template->getSiteMenu()->setLink( ... ); etc..
I think this is really cool.
http://www.stampte.com
Indeed, separation and reuse are the keywords here.
The best way to develop and to segment the work load within a team, is when the Web Designer (integrator/html-ist and so on) has no chance of breaking down the programming part (database, files, sessions, syntax errors and so on).
I recommend using the FigDice Template Engine, which operates a very neat separation between the Logics (program, database, files, algorithms, etc.) and the Presentation (the views and the information they present) in total security.
FigDice supports of course macros (reusable parts of a file), inclusion, iterations, and many more features, and also provides an exclusive approach to the Presentation/Logics separation, with the inversion of control of the data-providers (the Views pull the information they need to display, rather than letting the controllers push the data into the templates, as is usually the case with virtually every template engine).
This makes it possible to the HTML Designer to really decide what he wants to present and when and how, without any risk of breaking down the code.
I would be happy to get feedback and comments.
Thanks
I recently discovered the PHP framework Kohana (which is awesome) and was reading a thread about using it in conjunction with a templating engine such as Smarty or Twig. My question is why bother? Surely an MVC framework, by definition, is a templating engine. Even "raw" PHP is, arguably, a templating engine. What possible benefits are there of adding another level of abstraction on top of what's already present in a framework such as Kohana?
EDIT -
I realise that an MVC framework isn't the same thing as a templating engine, but surely the V part does the same job? Perhaps a better way of phrasing things would be; why add an templating engine on top of the V part of an MVC framework?
I have two really good reasons I can think of for doing this...
Creating markup that is repeated throughout the site in a consistent format is easier, plus you can update it later without a lot of grepping.
If this is for a real company, the people determining content aren't likely to be really familiar with HTML, much less PHP. Having a simple template language that keeps styles looking the right way and generates valid markup without much code knowledge is really handy.
Firstly, raw PHP is NOT a templating engine.
Next, MVC framework defines that the framework is split into Model, View and Control. It does not mean that the framework has a template engine, though the View may be integrated with a native or external template engine. Thus the framework may or may not have a templating engine.
Thirdly, View != template. View is only referring to how data is displayed - there is no template involved usually, whereas template engine refers to a piece of code able to put data nicely into templates - which you can greatly reduce the need to modify all files when you can modify them in the templates
Lastly, framework users may prefer to use a more common templating engine such as Smarty over the native template engine in the framework. You do not need to learn the new tags in the native template engine.
Unless you allow for short tags,
{$foo}
is much more readable than
<?php echo $foo; ?>
Multiplied over a large project, it adds up.
One big reason why you would want a separate template engine is because raw PHP is a bit too much for the presentation of your site. If it's just you making your site, and you have a good idea about how the site's templates aught to fit together, then this isn't really a downside, but for larger projects, it gets in the way.
If your project has outgrown a single developer, or if you want to add designer even before that, PHP is probably too hard a language to express the presentation in. Purpose built template languages are at the advantage because they are simple, and don't give you so-much rope as to hang yourself.
Larger projects, even when they don't require much input from multiple developers, can make the free-form of plain PHP a bit unwieldy. the purpose built template engine provides (or enforces) a basic structure to how each template fits with the rest.
Mauris has already covered why MVC != template engine, but I would like to add that the more powerful the template engine is, the cleaner and more concise your templates are. This makes it especially easy for people who are not familiar with PHP to edit them (e.g.: if a designer/front end developer needs to edit the HTML). In general, MVC's don't boast this sort of functionality.
Take a look at this example from Smarty. I've never used the engine and answering this question is the first time that I've ever seen its markup, but I can already tell exactly what its doing.
Further, the amount of code that you have to write is noticeably less since Smarty and other engines take care of mundane things for you like alternate row colors and alternate content for empty data sets in the first example, and silly things like formatting <select> lists in this example.
MVC implements the management of PHP templates, if you work in a team with web designers could be better to use HTML templates. Smarty and Twig are famous and good.
Anyway just choose the template engine you feel more comfy with.
I'm going to write a CMS, but right now I'm writing down all my ideas and trying to get all of my concepts straight before I start. One of the things I'm torn on is whether to use a template language and parse the pages of the website, and replace template tags with content items, or just develop the site with straight PHP and have the CMS generate data structures which help. For example:
{navigation: products}
vs.
foreach($cms_label['products'] as $product) {
echo '<li class="product_nav">'.
'{$product.name}'.
"</li>\n";
}
The former is cleaner but it would involve inventing a language, plus parsing every page before display. The latter is less clean but I think it could work really great if the CMS just provided data for all the code. But, would this be considered mixing logic with presentation? Another alternative I've considered is using PHP functions that are similar to the template tags:
<?php navigation('products'); ?>
What are your thoughts?
Keep in mind I don't have to do anything more complicated than including a page at a certain place, or writing out an unordered list; the rest shall be handled by CSS.
Template languages for PHP are an example of an anti-pattern called "Inner-Platform Effect." Smarty is an example of a template framework for PHP, but even Hasin Hayder, author of a book on Smarty says that Smarty is dead and there's no need to use it anymore.
There can be good reasons to develop a template language, for example if you are having non-coder designers or content editors using your CMS and you don't want to overwhelm them with the complexity of PHP (or allow them to write code that could break your website).
But you haven't described that as a goal, so I'd assume using PHP as your page template language is best in this case. It'll be less work because you don't have to develop your own new language, and it'll provide greater flexibility for uncommon cases where you need a specific kind of dynamic content.
Don't write PHP functions to encapsulate blocks of HTML output. Instead, use include() to pull in fragments of HTML. This technique is sometimes called "partials."
You can also use an MVC framework such as Symfony, Kohana, Solar, CodeIgniter, or Zend Framework to help you keep discipline about separating your PHP template code from the rest of your application code.
I was a very happy Smarty user for a long time, I don't believe in specialized template languages any more.
A template language won't prevent you from putting inappropriate logic in your presentation code, it'll just force you to write bad code in the template language.
It's fairly trivial to roll your own little template system that uses php in the templates. Then create various helpers to keep your template code clean (like your "navigation()" function).
I think the approach taken by Zend_View is pretty good. Symfony's view-layer stuff is fairly neat too, but might be a little intimidating. You don't have to use a framework to get something from it. Just look at some of the template code in the examples, and see what inspires you.
Bottom line: forget about a special language for templates -- just apply good design sense to your view code, factoring complexity out of the view scripts and into reusable helpers.
Reinventing the wheel is most of the time a bad idea.
PHP is already a templating language. You don't need to implement your own.
As for Smarty it is the most complete templating system for php and it is still a bad idea.
A couple of articles on the subject:
Once upon a time there was Smarty! by Hasin Hayder. He actually wrote a book on smarty and he doesn't recommend it.
Php and Templates by Harry Fuecks (Author of the 1st edition of the php Anthology)
If you want to look at templates done better look at:
phpSavant it uses php code and still promotes separation of concerns.
The final objective is of course to have easier code to maintain by promoting separation of Business Logic and Presentation
You might want to look into Smarty- http://smarty.php.net Smarty is a very powerful template engine that gives you the best of both worlds. It has extensive support for custom modules and plugins.
I built a custom CMS with Smarty and PHP and have nothing but good things to say about it.
The php code to use Smarty looks like this
<?php
// my cms
$smarty = new Smarty();
.
.
$smarty->display('home.tpl');
?>
The template code is something like this
<h1>{$pagetitle}</h1>
{insert tag="navigation"}
I wonder why noone mentioned what is one of the most important uses of a template language: automatic output escaping.
It's easy to forget a htmlspecialchars() here or there, so a template language that provides directives like {$name} has to make sure $name is automatically passed through htmlspecialchars, with the appropriate charset and everything.
Of course, that also implies that you can specify a different "context" for variable output, such as e.g. alert('Hi {$name|context=singlequotes}!'); where the template interpreter would escape $name's content so that it is impossible to break out of the single quotes, instead of XML escaping it (which should be the default).
Such contexts can also include stuff like int (to force a number), and it can also be extended to accept additional parameters to format the output, et etc.
My 2 cents. Not sure if there's an open source solution that allows for this (would be interested to hear about it!), I rolled my own interpreter for this stuff at work. Since the resulting "intermediate code" is pure PHP, it can also very easily be "cached" (like Smarty and other tpl systems do).
I pretty much like Smarty and I also think controllers should be purely written in XML and models in YAML. This is the only way to enforce MVC.
If the question of performance arises only then compilation to php might be considered as a possibility (albeit a remote one) with the sine qua non condition that it's done in an obfuscated fashion, to thwart eager developers from reading it.
I found that using Smarty with PHP, sometimes extra time will need to be used for
1) using quite different syntax than PHP itself
2) need to check small cases, because documentation doesn't give finer details, such as for "escape"
http://www.smarty.net/manual/en/language.modifier.escape.php
it doesn't say escape:"quotes" is for double quotes only or for single quotes as well, so you need to write code to test it. Also for the case of escape:"javascript" -- can't tell exactly what and how it is escaped.
3) for something complicated, need to write helper functions or modifiers, so it needs a creation of new files and ending up doing it in PHP again.
by the way, does using Smarty provide a good speed up over use PHP alone? thanks.
First, PHP is a templating language. Keep that in mind when you talk about using a template system for your PHP-based web applications.
The only 'real' argument that I've ever heard for using ANY templating engine was that they provide a simpler language for template manipulation which can be handy if you have template designers who don't know PHP and whom you don't trust to learn to use PHP judiciously.
Regarding these arguments, I would argue that if your template designers are not competent to learn enough PHP for template design, you should probably consider finding new template designers. Additionally, PHP itself provides a different syntax for control statements that you might use in a template versus in code. For example:
<? foreach($array as $key => $val): ?>
<?= $val ?>
<? endforeach; ?>
VS:
<?php
foreach($array as $key => $val) {
echo $val;
}
?>
Personally, I believe that templating engines arose in PHP because:
That's way that other languages do it
Better PHP programmers realized that they needed a way to enforce separation between presentation and application logic and templates were an easy way to do this.
The first reason is just kinda silly. The second reason can be overcome with a little self-control and even a rudimentary understanding of the necessity of separating layers in an application. The MVC design pattern is one way of approaching this problem. As far as exercising some self-control, my rule is that only necessary loops and if statements get used as well as functions that filter, escape, format the output for the screen.
Having used Smarty extensively, I can honestly say that it always presented me with more hurdles to get over than it did solutions. If anything, switching to PHP-based templates is what has actually decreased development time for both templates and code.
I don't like templating engines. I find them very lossy and resource-intensive for PHP.
With MediaWiki, around version 1.6.x we backed off using Smarty by default and just use PHP's built-in templating, with a great improvement in performance.
I've found that most of what people want to do with a templating system (add links, change colors, remove text or sections of the page) are better done with a simple system of event hooks.
Laconica, the open microblogging platform, doesn't do any templating by default. We have a plugin for people who are crazy for templating.
Smarty is certainly one of the best template engines out there. In my experience though people would be well advised to think their use cases through more thoroughly before they use any templating engine on top of PHP at all.
First, PHP itself is perfect for templates. Pretty much the only justification for using another templating engine is if you're allowing untrusted users to create or edit templates, since they could execute all kinds of badness. So, if your project has user-editable templates, use Smarty. If not, stick with PHP.
If your problem is separation of code and layout, I suggest you look into implementing a lightweight MVC-style execution model. Or, to put it more condescendingly, if you have deeper logic code in your template, it's probably time to do some refactoring.
Performance is another consideration. Yes, rendering a Smarty template comes with a cost. But after it's done, the output should be cached, leading you to improved execution times. Same goes for PHP templates. PHP allows you to implement all kinds of granular caching models through the use of its output buffers. But beware of premature optimization: do that only after you're code complete and have identified what the actual bottlenecks are!
The biggest cost when using Smarty or any other engine comes in the form of developer time. It's another layer of complexity and inevitably you will find yourself in situations where you have to trick the engine into doing what you could have accomplished within pure PHP all along.
I like template engines and think they should be used, but in the particular case of Smarty, I think it's waste of time, because it's not a significant improvement over PHP as templating language:
The new syntax is still based around old concept of special tags inserted in random places in the document.
Because Smarty does not understand HTML's syntax/structure, it cannot not help you to create valid/well-formed HTML. Smarty's tags violate HTML's syntax, so once you add them, other standard tools can't help you either.
Smarty's output, just like in PHP, is insecure (unescaped) by default and you have to remember to add |escape everywhere where you output data in HTML.
There's one particular PHP template engine that I've fallen in love with, which fixes all those problems: PHPTAL.
It's still something new you have to learn, and it's a depenency for your application, but I think having XSS and ill-formedness problems solved makes it worth the trouble.
PHPTAL just like Smarty is compiled once to PHP and cached, so performance is comparable to raw PHP.
Pros
No PHP in your HTML files (Allows both PHP and HTML identing)
Pipes {$var|default:"None selected"} {$var|urlencode}
Foreachelse: {foreach item=row from=$results}{$row.name}<br>{foreachelse}No results{/foreach}
Themable websites/pages (Using only CSS has it limits)
Cons
Other language syntax
Not always obvious code {"Y-m-d"|strftime:$timestamp} {$array|#var_dump}
Slight overhead
I can highly recommend the "template" approach(mVc), but both Smarty and plain PHP are up for the task.
As far as I know Smarty is one of the best template engines speed wise. Maybe it takes a while to get used to it. But if you are not working on the system alone and the amount of html and style files is huge it speeds up the development significantly.
While working on my last project the design was changes a couple of times but logics was the same. I guess that's the best example when Smarty or any other template engine helps a lot.
Personally I use Blitz for templating. On the site the author claims it is the fastest templating engine and provides a (biased?) chart over performance between different templating systems for PHP. I haven't used smarty myself, but this may give you some hints on its performance.
http://alexeyrybak.com/blitz/blitz_en.html
Using Smarty as a templating engine will probably not be as performant as not using it, as it is an extra layer of software, i.e., a templating language on top of a, erm, another templating language. On the other hand, if you use the caching feature properly you could realise overall performance gains.
Smarty templates are pre-compiled before being output to the browser, which involves writing temporary files to disk. This step surely penalises performance, at least a little.
If you are confident in your ability to keep implementation and presentation separate, and have no real interest in server-side caching, you should probably just use pure php templating. Some MVC frameworks such as Zend Framework have their own PHP-like templating systems.
On the other hand, smarty is a decent way to enforce a neat separation of presentation from implementation, particularly where it's unclear as to what belongs where. It might help discipline you to enforce this necessary separation.
That said, I use Smarty in most of my PHP projects, as it reminds me of Java-Server Tag Libraries (JSTL), which I'm very, very used to, and fond of.
Using a Smarty or not is more or less a philosophical position.
I use it, although I don't use much functionality. Using it this way, templates tend to be be very simple. Pass an associative array with parameters, iterate through its components and insert required elements in the result page. This keeps templates clean and (hopefully) free of business logic.
Additionally, extending Smarty is quite simple.
As an example, I added a styles parameter to the fetch() to have a fetchUsingStyle(). This allows me to switch between different layouts of a site quite easily.
Furthermore, my fetchUsingStyle() searches various locations for a template: First tries to find the current style. If not found, it tries to load the template using a default style. Last, it tries to locate a pure static dummy file, a placeholder for something to be implemented later.
Try to Use Smarty with MVC pattern such as Codeigniter , Its better than core PHP
Why use a template engine when you can just use your html files and inject php code where you need it? you can do this with Psttt! templating engine for php
full source code here http://github.com/givanz/psttt
In the past I've written sites in ASP.NET just to get nice reusable templating via master pages (layouts) and user controls (partials). I'm talking about sites that have no more complicated code in them than simple variable substitution in templates - I'm just using it to keep my HTML organized. It's great to be able to define the basic layout of your page in one file, and then just fill in the holes for each individual page, re-using some common bits as user controls.
However, I'd rather not continue using Windows hosting, so I'd like to write static pages in PHP, which runs everywhere. In the past I've written myself a poor-man's user control for PHP that just unpacks an array and includes a template, but that's clunky and still requires me to put PHP includes all over my pages. I feel like Smarty or one of the other big templating languages for PHP is overkill for just organizing some "static" pages.
I've considered just doing the pages in Ruby on Rails because I really like HAML/SASS and the layout/partial model, but having a whole rails app for static content seems silly. But I haven't found anything that seems just right in PHP. Can any PHP gurus recommend anything? I want something more sophisticated than "include" but I don't really need much. That said, something that could give me layouts/partials AND HAML/SASS would be heaven. I've looked at phammable but it doesn't look like it solves the layout/partial problem.
Again, I'm not looking for something as complex as Smarty, and I don't want a full CMS. I just want something that will let me properly modularize the HTML of my site. We're talking one step beyond static HTML here.
Zend_View supports layouts, partials and placeholders. Also checkout a new templating language called Dwoo which is similar to Smarty but also takes some ideas from Django templating. And finally, Calypso which is a Django template language clone for PHP
If your looking for something simple I would recommended PHP Template Inheritance. Then you can continue to code in straight php.
I just want something that will let me
properly modularize the HTML of my
site.
Look at http://code.google.com/p/hoduli/
With that simple tool you'll be able to write like this:
<h:define name="header">
some header contents
</h:define>
...
<h:header />
<h:include file="middle_part.php" />
<h:footer>
some ...
</h:footer>
I would suggest to you to look at Drupal and its Block templating model. I think its just what you need.
Stacey is about what I was looking for in terms of a simple PHP templating library for static sites.
On the Ruby side, there's StaticMatic, which doesn't even require Ruby support on the server since it generates the whole static site. Very nice (especially since it uses HAML) but you can't have any dynamic elements at all.
From what i understand, you don't want a full fledged cms and no overkill templating engine like Smarty. Php is a templating system and if you want to properly modularize it, that's up to you.
But i understand, those php tags between your html doesn't look pretty. (Although using shorttags minimizes this...)
You can always use PEAR Templating system, it's available by default on most php installations.
I would also recommend the CodeIgniter MCV framework because it's really lightweight. You choose which libraries get autoloaded.
About six months ago, I started using the Zend Framework. I got used to working with layouts and partials, and never wanted to go back creating sites without it. But for small sites, ZF is just too bulky. It's overkill to use ZF for a site that could be done in HTML.
Check out EuropaPHP. It's a super lightweight, PHP based layout framework. It's brand new as a framework, but so far, I like it a lot! It allows me to use layouts and doesn't require a huge library and strict rules to achieve the same results.
Maybe you should take a look at some content management systems. Drupal is famous in PHP.
Drupal really is a simple and extensible CMS. There is a learning curve, but it's strengths are that is starts small out of the box and can grow with your needs and the community is pretty tight about the quality of the code that's written (though I personally find that some of the modules get a little two function happy).
They have a simple stripped down version of the Zen theme, that lets you create the HTML you want to use. Time spent learning this CMS is time well spent, especially if PHP is already your native language.