Related
While I have been reading through countless posts about using PHP as a template engine (using output buffering), I'm still trying to make a case for it.
As I'm wondering if I could use PHP as a template engine for a web app (users will be able to change the layout themselves) -- I still don't find any info regarding the following:
Store the templates in a MYSQL database
Eval them
BUT only include functions that are whitelisted (to give them only access to a limited set of functions -- while, foreach, etc ...)
Anybody looking for the same solution, but can chime in with a bit more information? That would be quite nice.
If you can't trust the user editing the template, you are better off using a separate templating language.
Note that many template languages like Smarty provide code execution functions as well. You may need to disable those in the engine's configuration.
Disabling all potentially dangerous functions in PHP is a very arduous task, and easy to screw up. See Exploitable PHP functions
PHP is not suitable as a template engine for your purpose. You should use a proper template engine with sandboxing support for that: Twig.
That is probably a quite difficult (but interesting, if you are into the topic) task, because it involves building a small PHP parser, which can flawlessly identify any function call or method call (because if you miss one, you're screwed/hacked/...) and then check if all your matched function identifier tokens are in your whitelist, and otherwise deny eval-ing. For generating your Parser, you might want to check out the PHP_ParserGenerator, which unfortunately does not seem to be maintained anymore, or lemonPHP/JLexPHP, which may be more up to date, but you need to use Java to generate the Parser.
Because of all this is a quite tedious task, most people resort to using a custom (made-up) template language, which is similar to PHP, but not identical.
Popular PHP template engines are, among others:
Smarty
Twig
PEAR Template Engine
Savant
More can be found here and here
I want to embark on a social network project. And i want to use PHP as the programming language. But am confused on which template engine to use when it comes to performance and security wise.
Do you absolutely need one? Any templating engine will be slower than plain old php.
Take a look at Twig http://www.twig-project.org/
And when you want to have Auto Output Escaping with Objects in the Template System like in Symfony 1, even plain PHP could be slower then a Template System.
I highly recommend Mustache. It is simple, fast, and cleanly separates your template from logic. Systems like Twig and Smarty allow far too much logic in the template.
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.
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
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