What's a good templating system for PHP? [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
What's the best/easiest to integrate templating system for PHP, and what are the benefits of using one?
I currently don't use one at all, and am thinking that it might help to seperate content from presentation a little more.

PHP is a pretty good templating language by itself. Most leading PHP frameworks don't use a seperate templating langauge for just this reason.
Just make sure you use (something resemebling) MVC, and don't do any data access or business logic inside your view files.
I've also used Smarty extensively, but find it has little advantage compared to straight PHP, except for forcing you to keep your view dumb. It might also looks a little better to designers, but the down side is flexibility to you, the template implementor. Things like looping over triply-nested arrays become harder than with straight PHP.

Smarty
I've found it to be fast, easy to use, and easy to install (even in a shared-hosting environment). It also doesn't require that you use validating XHTML which is handy sometimes (although I think the template engines that do require valid XHTML are probably faster.)
It's really nice to have your content in one place and code somewhere else.
Plus you're not limited to just HTML. I've used Smarty to generate XML and even SQL.

To follow up on what Alex said, I suggest taking a look at Rasmus Lerdorf's article The no-framework PHP MVC framework.
Rasmus Lerdorf is the guy who created PHP.

I bet on PHPTAL.
It checks file syntax and ensures output is well-formed XML with proper escaping. This ensures that pages are safe against XSS attacks without programmer having to worry about it every single time.
Smarty and raw PHP don't handle escaping automatically, which means that every echo $foo or ${foo} (without |escape} or htmlspecialchars()) might be HTML injection vulnerability or at least break well-formedness.
PHPTAL has nice syntax that fits how HTML/XML work, e.g. you don't have to repeat yourself when you want to conditionally wrap something in a tag:
<strong tal:omit-tag="condition">
xxx
</strong>
rather than:
{if condition}<strong>{/if}
xxx
{if condition-again!}</strong>{/if}
And the syntax is XML without being overly verbose (mostly only attributes are added). There's no ugly mix of HTML and custom tag-like constructs.

In addition to Mark's experience, I've found Smarty well-suited for extension. I've built a (corporate) MVC framework with built-in views based on Smarty which was both easy and is flexible. The host of available template helper functions can also be extended very easily.

Perhaps the most compelling reason to use a template engine is default output escaping which can reduce or eliminate xss vulnerabilites.

It depends on your focus: different template engines can be better for different things. Smarty is relatively heavy compared to some, and defines a syntax that is simpler but more restricted than PHP's. There are benefits to using a syntax that is less like a programming language, for example if you're going to be asking a graphic designer to build your templates.
A template engine such as Savant3, or that used in the Zend_View components of the Zend Framework is lighter-weight and uses PHP as it's syntax. This gives you more power and flexibility in your templates, but requires you to be disciplined about keeping business logic out of the templates. Also, PHP syntax may be too complex for your designer, if he is going to be building the templates.

I personally like the idea of just using separate PHP/HTML files. It allows me to use other HTML editors if I want (such as DreamWeaver) and can also allow people who don't know PHP, but do know HTML to edit the templates without having to learn another language.

I have used Smarty for years, but got frustrated because the special smarty syntax got in the way, where some simple php would be way easier. PHP itselves is in its very core a template language! I learned that the php api is apt enough for all presentation logic.
Savant3 and its descendant Zend_View are therefore superior solutions. Like in Smarty, you can easily write plugins for repetitive tasks.

Related

When to use PHP template engines [closed]

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

Is MVC now the only way to write PHP? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 12 years ago.
Improve this question
The vast amount of frameworks available for PHP now use MVC. Even ASP.net has its own MVC module.
I can see the attraction of MVC, I really can and I use it frequently. The only downside that I can see is that you have to fire up the whole system to execute a page request. Depending on your task this can be a little wasteful.
So the question. In a professional environment is this the only way to use PHP nowadays or are their other design methods which have alternative benefits?
I don't like anyone telling me how to write a code. If I want to use MVC I will, if I find a better way that solves specific task, I will use it. I don't like when people turn MVC into a religion. I also think many php coders misunderstand the MVC concept and think they are using MVC pattern when in fact most of the times that are not using a 100% pure MVC. The truth is that it's not easy nor very efficient to write a website that is 100% MVC and is written in php.
Most people having most difficulties in the "V" part of the MVC. The "M" is easy. It's your data. If you storing your data in the database and have a database access class, that's your "M" part, you good with "M"
Now the controller: when user clicks on any link of your page, your php code must get the data from the "M" (database), prepare it, apply some logic like adding personalization to logged in user, adding "please login" link if user not logged it, etc. This is your "C" part.
The problem that most people are having with is separating the "V" View from "C" (controller) This is not easy nor is it the most efficient way to code in php. In many cases the controller part must already generate some html, so you blur the line between controller and view.
If you want to stay pure MVC then you must make sure that your controller returns a pure data, then the View class takes some template, plugs in your data and returns the HTML. This is where the problem lies in php. There is no easy and efficient way to do templating where a template just takes a pure data as input and returns the html. If there was an easy way, then there would not be reason for people to keep coming up with yet another new template library. The reason the there are so many templating libraries for php is because there are always programmers that are not happy with ANY of the existing ones and keep trying to invent their own, better one.
The only pure templating library in my opinion is the XSLT, which is fully supported by php, it's comes with php, it works, it's powerful, great templating engine, better yet, it's a standard, platform independant language. Once you learn XSLT you can use it in any other programming language like Java. But it does have one tiny problem, however. It requires the input to be an XML. Sure, you can create a great, 100% valid XML in php also using DOM library which is also part of php. The problem is that it will be slow. You will be doing double the work: first creating XML from your array of data, then trasforming that XML into HTML with your XSL template. This is why the approach of XSLT as templating engine never took off in php.
Now you left with the other options to parse templates, usually its regex based approach. You see how it always gets complicated when we get to the "V" part of the MVC?
The "M" is easy, the "C" is some type of pure php code, be it OOP or procedural code, does not matter. It's the "View" that is the tricky one.
So my advice is - don't worry too much about sticking to pure MVC. It's OK for a controller to spit out chunks of html here and there.
Well there are a lot of other approaches.
MVC is just popular because it suits most situations (or better said can be used in most situations) and has established itself as a de-facto standard.
What can be said is that every programming/design pattern - or more specific architectural - depends on some classification.
Those are often (of course they can be devided further):
User Interface (pretty images, forms etc)
Application (your application logic and stuff that needs to be secured from the client - ak lot of that can often be done in the user inteface, eg. by javascript)
Database - self explaining
Infrastructure (very basic stuff like hard disk, server systems, network etc.)
Of course there is always the naive, procedural straight-forward approach but also a lot fo other patterns that can link and structure the access and controlling to these basic layers.
Mvc is one of them. But here are some example of others:
http://en.wikipedia.org/wiki/Model_View_ViewModel
http://en.wikipedia.org/wiki/Model_View_Presenter
Is MVC-ARS preferable to classic MVC to prevent overloading?
And here a lot more:
http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)

Why do almost all PHP framework use "<?php echo ... ?>"

The PHP short tag <?= $var ?> has been deprecated for a while.
Almost all PHP frameworks use the long form <?php echo $var ?> (e.g., symphony, Yii, Kohana)
Smarty is a famous PHP template engine which supports a shorter form {$var}
Template engines (like Smarty) are easier for web designer
Editing a template shows {$var} instead of showing nothing (because of <..>)
Shorter syntax (less typing especially when <> are on the same key on some keyboard layout)
The templates are pre-compiled and cached giving nearly the same performances
All those points make me wonder, why do all framework seem to use the super long PHP syntax? Is there a strong point of not using a template engine like Smarty (except the small overhead)?
The thing about PHP is that it already is a templating language.
Smarty, as nice as it is, is added overhead. If you don't have a good reason to use it, then why would you? People who use backend frameworks are developers who are already familiar with PHP, so there's no reason to make them use a templating engine with a new syntax to learn on top of it.
Most frameworks are flexible enough that adding a template engine doesn't take much work. If a framework was built that forced you to use Smarty, then it's going to be less popular, because the framework itself would be less flexible.
In regards to the "long syntax", no framework is going to hang their hat on a deprecated syntax with security issues. It can be left up to the user of the framework if they want to use it or not (which no one should be these days), but building a core framework around short tags makes it less portable.
I don't know that I would call <?php print $foo; ?> "super long syntax."
The fact is that short-tags aren't always enabled on servers, whereas the standard default typically is. It's safer going that route.
Template engines like Smarty add an additional layer of processing that is not needed - they are mostly bloatware. They usually add too much additional processing for what amounts to syntactic sugar. Using a template engine when full PHP tags are available is like wearing shackles - it becomes another language with it's own quirks to learn in order to accomplish the same thing with regular PHP.
In my experience I've rarely seen a non-programmer fully or easily utilize a template engine. Take these two instances:
Smarty:
<select>
{foreach from=$k item=v}
<option value="{$v.value|escape:'html'}">{$v.label|escape:'html'}</option>
{/foreach}
</select>
PHP:
<select>
<?php foreach ($k as $v) { ?>
<option value="<?php echo htmlentities($v['value']); ?>"><?php echo htmlentities($v['label']); ?></option>
<?php } ?>
</select>
Now, the Smarty syntax may be slightly cleaner - but honestly, is anyone except a programmer going to be able work with either code set comfortably? Template engines add an extra layer of processing/logic without offering any major benefits.
Here's what Fabien Potencier of the Symfony framework has to say about templating engines:
Why do people still think PHP is a
templating engine? Sure enough, PHP
started its life as a template
language, but it did not evolve like
one in the recent years. If you think
PHP is still a template language, can
you give me just one recent change in
the PHP language which enhanced PHP as
a template language? I cannot think of
one.
He also describes the features that he looks for in a templating language:
Concision
Template oriented syntax
Reusability
Security
Sandbox mode
As well as some of the features that make his favorite templating language Twig stand out:
Native template inheritance (templates are compiled as classes);
Solid automatic auto-escaping (with no associated runtime overhead as
everything is done during
compilation);
Very secure sandbox mode (white-list the tags, filters, and methods that
can be used in templates);
Great extensibility: you override everything, even the core features, by
bundling your own tags and filters as
an extension; but you can also
manipulate the AST (Abstract Syntax
Tree) before compilation. By
leveraging this possibilities, you can
even create your own DSL (Domain
Specific Language), targeted at your
application.
In the comments of the article, he says that, "It will probably be part of Symfony 2. But I first need some community feedback."
Read the full article to get his whole argument in favor of templating systems.
There are some reasons:
They are to be deprecated from future versions of php due to security concerns.
Some hosts disable them.
More:
Are PHP short tags acceptable to use?
They're not recommended because it's a
PITA if you ever have to move your
code to a server where it's not
supported (and you can't enable it).
As you say, lots of shared hosts do
support shorttags but "lots" isn't all
of them. If you want to share your
scripts, it's best to use the full
syntax.
I agree that
I don't buy readability as a reason at
all. Most serious developers have the
option of syntax highlighting
available to them.
More
http://terrychay.com/article/short_open_tag.shtml
Short open tags are not deprecated and they will also not be removed in PHP6.
[PHP-DEV] Throwing an E_DEPRECATED for short_open_tag
[PHP-DEV] Re: Is it true that short_open_tag is deprecated in PHP 6?
[PHP-DEV] short_open_tag
Request for Comments: Improved short tags for templating
The linked articles also contain lots of useful information about the topic.
Quoting Rasmus Lerdorf (3rd link):
Most of the arguments I have seen are basically saying <? is evil and it shouldn't even exist, but that isn't the current question. It does exist, and we aren't removing it, so the only real argument here is the WTF factor introduced by code that is able to enabled or disable these tags on the fly. That's the one and only valid argument I have seen. Whether or not PHP code can be validated with xmllint and whether or not <? is valid xml, which it obviously isn't, is completely beside the point. We all know that when you use <? you are not XML-compliant. And for the vast majority that's ok. […]
My view is that people want templating. As much as I hate the concept, and have always been very vocal about that, people want simpler templating tags. They will even go as far as parsing files and generating PHP code on every single request in order to use {blah} instead of <?php blah() ?>. The fact that people are willing to take an order of magnitude performance hit for syntactic sugar is baffling to me, but just look at all the templating systems out there. And yes, I know there are other reasons to use templating such as restricting the feature set for untrusted template writers, etc. but you'd be surprised how many people just want to type less and have their tags be prettier. Getting these folks to switch to <?blah()?> is a win for performance and sanity in my book. Yes, it isn't a full victory, but it is still a win.
Personally, I try to avoid templating systems as I find regular PHP syntax much easier to use as a templating language that reinvents what PHP can do out of the box. With the addition of ViewHelpers, any designer shouldn't have too much trouble using regular syntax. Actually, I always found the argument, Template engines (like Smarty) are easier for web designer pretty belittleing. The verbose PHP syntax might not be appealing aesthetically, but any half-brain can learn it.
Because they don't want to include a library as huge as Smarty to make their templates a few characters shorter.
In addition to the other answers there are a couple of things that make Smarty (and similar template engines) problematic.
The first is that you need to escape some characters in your template if you're going to put javascript in it. If your javascript is dynamically created by PHP, it gets even worse; the readability of that code goes down drastically.
The second and most important is that when you're working in a decent OO framework Smarty will severely decrease the functionality of your code. When using PHP as your template engine you can use $this within your template to call methods in the controller that's parsing the template. Not only that, but you get access to all the methods that controller has inherited.
With smarty you lose this entire functionality because $this no longer refers to your controller. In essence, instead of accessing your entire framework from your template, you only have access to Smarty's limited functionality.

PHP vs template engine [closed]

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

how to use Smarty better with PHP?

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

Categories