The article is old, but I think is still relevantToo often I have heard the word "template engine" lately. Disputes between supporters of different template engines do not subside. Some say that the logic in the templates is good, others consider it to be evil. Even now, very often there are projects written without any template engine at all. But in this article I will not attempt to side with one of the parties. I will not prove to you the advantages of any of the approaches. I will simply try to tell about all of them from the point of view of theory. This article is not about specific software products, but about how to highlight the presentation logic in your applications.
TermsThe article uses a number of terms that you may not know. I will try to define some of them.
')
Representation - application logic responsible for displaying data. For web applications this is the logic that forms the HTML page.
Domain - The part of the application responsible for data processing, that is, containing the business logic of the application. The expressions "business logic" and "domain logic" are essentially synonyms.
Template - A file containing HTML and some markers that allows this template to be processed and form the final HTML code based on it.
Template engine is an application that processes the template.
Pattern, Typical solution - solving common problems.
Template Designer as a MythThis is just a term describing a class of programs that replace string sequences with some data. And the slang term. In fact, everything is much more complicated, and requires a deep and thoughtful understanding of the subject area. We will come back to this, but now let's consider the essence of the problem.
The fact is that the word "template engine" is often considered a synonym for the word "presentation". In absentia, it is believed that if you use a templating engine in your projects, then you separate the presentation logic from business logic. Some even think that template engines are designed for designers / web designers, and the programmer doesn't need them. So, all this is a myth. A template engine is a program designed to make the separation of logic more convenient, providing some advanced functions, but it is in no way a stumbling block. You can use any template engine or you can do without it at all, but at the same time it is good to select the view from your application. And vice versa, you can use Smarty, but at the same time, you can completely confuse everything and twist it. Therefore, saying that you use a specific template engine, you only convey to the fact that you are using some kind of software product, but this does not at all indicate how well your application is written.
Separation of HTML and PHPIt all started with this. Any one of you remembers those timeless times when everyone around was in awe of PHP's ability to penetrate HTML code, becoming part of it. This made the understanding of the language much easier. Many even thought that HTML and PHP brothers working together hand in hand (many are still sure of this). Even those who understood that PHP actually knows nothing about HTML (as well as HTML about PHP), and only displays the text, were glad that they did not have to write a bunch of print. Everything is so simple!
And this simplicity gave rise to the problem.
BorschtBorsch only at first glance seems chaos. In fact, well cooked borscht is delicious. But if you add a little more cabbage, more salt and a little water ... It will not taste good. In borsch, the main thing is not to overdo it (sorry for the pun).
Actually, no one wanted evil. Just a new language has attracted, of course, and new programmers. It is new, flattering on the simplicity of PHP, convenience and power. We then did not know about any MVC. We did not think about the problems of code maintenance, readability and stability. It worked, and we sincerely rejoiced at it.
But soon we realized that the soup becomes tasteless. At first, the foldable alternations of PHP and HTML became too complex for perception. Change of design in general turned into a nightmare. Thoughts about the fact that we already wrote this once became obsessive, but the place where this code was already written was extremely difficult to find. It was even more difficult to pull it out and insert it into a new project.
But enough of the lyrics. In different ways, we came to understand that you need to separate the HTML code from the PHP code. And here we learned the word "template engine".
What is a template engine?This is a program designed to separate PHP code from HTML code. There is an opinion this is necessary for designers. In fact, I have never had to deal with designers (excuse the layout designers), who would immediately create templates. But it's not that. In fact, programmers did not want to care about web designers. He himself is already tired of satisfying the new delights of designers, shoveling with all the code.
At this point, the programmer was already sick of any code mixed with PHP. At least I completely rejected any kind of logic in HTML. My template engine could repeat pieces of code (blocks), include other files, but there could be no talk of any logic. I spent the whole weekend writing my template engine. I was proud, and considered myself the most correct programmer. But soon the projects became more complicated. And even with all the power of my template maker, HTML still sifted through all sorts of ways into my projects.
Business logic and presentation logicFinally we get to the point. In fact, by highlighting the logic from the HTML code, we went overboard a bit. Trying to write correctly, which is commendable, programmers headed for the complete separation of PHP from HTML. As if only these 2 languages ​​exist in the world. But in fact, PHP and HTML are just tools. Moreover, the tools complementary to each other. You probably will not argue that HTML determines the appearance of your site. And PHP is committed to creating this view based on data. But can PHP and HTML be clearly separated? No, of course not! PHP still determines how your page will look like [[* *]]. It turns out that HTML is only a representation, and PHP is not only engaged in receiving data but also determines how, where and how much, to show them. We return to what we have left. It turns out to separate PHP from HTML is impossible? I will say more. And do not need!
In fact, the question is not whether PHP is separated from HTML, but where to separate them.
Presentation logicThe logic of any program can be divided into two components - the logic that receives and processes the data [[* 2]] and the logic that shows them to the user. The first is called business logic and the second is the logic of presentation. It is important to be able to clearly separate these 2 types of logics, so that they do not mix. With regard to web-programming, it can be said with absolute certainty that HTML refers to the logic of the presentation and the database is a matter of business logic. But between them there are plenty of PHP code. The difficulty is to divide this code. Finally, we come to the problem that prompted me to write this article. In fact, there has long been a stereotype that claims that PHP can not be part of the display logic. This stereotype appeared for a reason. Remember that once we interfered with PHP code and HTML. Then we learned that this should not be done, but we should use template engines. From this point on, we subconsciously draw a clear line between PHP and HTML, trying never to mix them. I'm not trying to argue that you need to mix. But you need to understand that PHP is also responsible for how the data will be displayed, that is, it is directly related to the presentation logic. It is important to understand that the question whether to mix PHP and HTML code or not to mix has nothing to do with the separation of two logics. You can mix and you can clearly separate, and at the same time say that in the program, these logics are well separated. Understanding this is very important. If you clearly distinguish between PHP and logic representation, then you are deeply mistaken. For example, Smarty, the most popular of template engines, does not use pure PHP in its templates. Nevertheless, it compiles its templates and as a result it turns out that it is a mixture of PHP and HTML.
Two types of presentationThe argument about whether to use logic in templates or not is forever. For even Martin Fowler speaks of two types of presentation layer: the template presentation and the [[* 3]] transformation view.
View by template (Template View)As an example, the well-known Smarty. Data is transferred to the Smarty templates, and the template itself determines how to display this data. But imagine that this feature is already built into PHP! Actually tell me what

Is PHP different from the Smarty template? How are Smarty ({}) tags not similar to PHP () tags? Yes, in essence, the same thing! Remember how more experienced colleagues told you that interfering with PHP and HTML is not good? So, you were deceived [[* 4]]. Perhaps those who told you about this and did not themselves understand that the PHP code and the Smarty code are twin brothers, perhaps you were simply warned against big mistakes.
PHP vs. SmartyIn fact, PHP in the hands of an inexperienced programmer really becomes uncontrollable. Remember the soup. If you do not know how to cook it, it becomes tasteless. PHP allows too much, and due to inexperience it may be tempting to cram templates of various logic into an inappropriate representation in PHP. For example, no one will prevent you from executing SQL queries in your code. Smarty, in this respect safer. Of course, in Smarty you can, skillfully, spoil everything. For example, write a function that executes SQL queries [[* 5]]. But all the same for this you need to make a lot more effort.
The second argument against php templates can be syntax. We have already agreed not to consider the problems of web designers here. Actually, {$ var} reads better than or, more correctly ,.
Another problem is the lack of caching. But this argument is only for projects with a high load. Of course, in this case it is easier to use an already ready Smarty than to invent something of your own.
All that I said above is not aimed at the fact that you would throw Smarty and urgently switch to plain PHP. You just have to clearly understand that the code in HTML does not mean bad. If you use it correctly, in the right proportions, then there is nothing wrong with that. This is just one way to divide the application into layers, and separate the presentation layer from the rest. I myself use Smarty, because I feel so comfortable. But I understand perfectly that Smarty is just a convenient layer, which, if necessary, can be removed.
ExampleThe easiest way to pass variables to a PHP template is to simply declare them, before including the template in the code.
$var = 'Hello, world!'
include 'template.php';
But this method has a number of inconveniences. First, such a transfer of variables is opaque (it is sometimes difficult to find the place where the variable was declared).
Secondly, if the variable is not declared, but it is used in the template, PHP will generate a Notice level error, and this is not always convenient (for example, Smarty does not issue notes). Thirdly, those who used Smarty got used to working with the object using the usual methods of Assign and Fetch. All these disadvantages are easy to get around.
Look at the code below and compare it with a smart code. Of course, all methods of the Smarty class are not implemented here, but this is not the point. The fact is that 90% of the required Smarty functionality is implemented in two dozen lines of code. Template engine in 20 lines! Apart from the PHP code itself :)
class PlainPHPView {
public $template_dir = TEMPLATES_DIR;
protected $Vars = array();
public function __construct($template_dir = '') {
$this->template_dir = $template_dir ? $template_dir : $this->template_dir;
}
public function Assign($var_name, $var_value) {
$this->Vars[$var_name] = $var_value;
}
public function Fetch($template) {
$reporting = error_reporting(E_ALL & ~E_NOTICE);
extract($this->Vars);
ob_start();
include $this->template_dir.'/'.$template;
ini_set('error_reporting', $reporting);
return ob_get_clean();
}
public function get_template_vars($var) {
return isset($this->Vars[$var]) ? $this->Vars[$var] : false;
}
}
You can use this code in the same way as smart. The only difference is in the syntax of the templates. But this is very easy to get used to.
$var = 'Hello, world!'
$view = new PlainPHPView('./');
$view->Assign('var', $var);
print $view->Fetch('template.php');
Transform ViewIn addition to the dispute whether to interfere with PHP and HTML or to use Smarty, there is still a no less fundamental, but no less useless dispute. The argument is about whether to put any logic at all into patterns.

There is no explicit logic [[* 6]] in the templates based on the “Representation with transformation” pattern. This is almost pure HTML. But before outputting this HTML, it is converted using some logic, and only after that is given to the client. That is, the presentation is determined not only by the template itself, but also by special code, this template processing. Martin Fowler gives XSLT XML data transformation as an example. I want to give an example more close to reality: FastTemplate.
In templates like FastTemplate, code defines logic. The template itself contains only HTML and special markers that mark parts of the template that need to be processed. The “converter” itself reads the template, and converts it into final HTML.
At the same time, in complex templates, it is very difficult to avoid the complete separation of PHP from HTML. All the same, for example, reference code, or form elements are easier to form in the converter script itself. And this is not a bad decision. In fact, both the template and the “converter” work together and are together in the presentation layer. But when using this pattern, it is even more important to be able to properly separate the layers, so that they do not mix. For example, it would be nice to arrange a “converter” as a class, thereby abstracting it from the rest of the code.
HelpersIn any of the approaches, a situation may arise when it is necessary to carry out the formation of typical representations in various templates.
For example, the formation of links, or form elements. In any case, it is most convenient to remove this code from a template and arrange it as a function of either a class or its method. As an example, the Smarty plugin system. Such functions are called “helpers” or helpers. In fact, try writing a code in a template that forms a calendar. Uvren you get it. But if the calendar is required in another template, or even a project? Copy + Paste is certainly an option, but not a solution. It is much easier to arrange such code as a class method. Of course this will complicate the design change, because now the look of your site depends not only on the template. But do not forget that a view is not only a template, but a whole set of classes and functions that lie in the view layer.
So what is a template engine?As I said, the template engine is a myth. The myth is not on its own. It is a myth in the context in which this word is often used. Probably you were asked at the interview, before applying for a job, about which template engine you use. The answer to "no" greatly reduces your chances of being hired. In fact, the employer had a slightly different mind. He wanted to ask you how, and not by what, you divide the application logic into layers. But in the view of many, unfortunately, the templating system and the logic of the representation of these words are synonyms, unless of course the last term is generally known to your interlocutor. Try to answer that you do not use template engines, but use a mixture of PHP and HTML. 5 to 1 that you will not take :)
ConclusionRemember how someone wise noticed that history tends to spiral, often repeating, but at a higher level? Code, we mixed the PHP code and HTML, then we learned that it was bad, but now it turns out that it’s not so bad. Once, I myself thought that the logic in templates is evil, and now I am writing an article about the fact that this is just one of the approaches.
In this article I did not follow the goal to change your views. If you like Smarty, do not give it up. If you adore FastTemplate and similar engines, this is also your right. Each choice has its pros and cons. The main thing is that the choice of the decision be based on clear criteria and full awareness of their weight in a wide choice of available options. Guided by the imposed stereotypes, you yourself deprive yourself of the right to make this choice. I hope this article will make you take a broader look at the problems that you face in the difficult task of creating web-systems.
- [[# 1]] For example, how many times to show a particular block, display text in 2 columns, display a table in which the lines have a different color ... plain HTML will make it difficult to achieve such effects.
[[# 2]] The application is usually divided into 3 layers, but in this article we will divide the application into 2 layers, the presentation logic and everything else.
[[# 3]] Fowler speaks of three typical solutions, but the third is the union of the first two. For primers, I’ll explain that Smarty is just about the third type, combining typical “Template view” and “Conversion view” solutions.
[[# 4]] Smarty does just that, compiling its templates into a mixture of PHP and HTML code.
[[# 5]] By the way, God forbid me to impose another stereotype on you. The presentation layer can easily select data from the database, bypassing the business logic layer, and even independently transfer this data, for example, for complex calculations, to the domain layer. Such templates are also called active. It is not the decision that determines the architecture, but the architecture that requires solutions :)
[[# 6]] The logic is there. But this is implicit logic.
community.livejournal.com/ru_php/789059.html** Charts taken from Martin Fowler site **
www.martinfowler.com