Once again about templates

Sooner or later, a developer who creates sites with a status higher than “site-business card” has to deal with such a concept as “templates” or “template” visual presentation (not design templates). What it is? The template mechanism allows you to separate the visual representation of the web application (since I work only with web applications, I will discuss in this context) from the business logic in such a way that when changing, for example, the internal logic, you don’t have to redo the entire html- layout In this field, there have long been several separate flagship solutions that allow you to create fairly flexible applications in terms of the division of labor of layout designers and programmers, as well as prevent code confusion in large applications. Describing all of them makes no sense. This has already been done before me, and more than once.

Of course, when it comes to a project of tens of thousands of lines of code, when the customer has the opportunity to hire both a programmer and a layout designer, then the functionality of the templates will be only good for all participants in the project. But when the developer starts to put Smarty into a simple website in 3 pages, this is IMHO a bust. In such cases, I like to recall George Schlosneigel’s expression from his wonderful book, “Professional PHP Programming” - “Attempting to kill a fly with a hammer”.

Indeed, integrating the same Smarty into a site that is very simple in functionality, the developer simply spends time. And time, as you know, is money. And in most cases, the customer doesn’t care on which template engine his site will work. The customer is more concerned about the time spent.

What to do if the site is not a "business card", but not a second Amazon? Personally, I believe that in this case, the optimal solution to the problem is to use your own self-written template system, the entire functionality of which is sharpened only to solve a narrow range of tasks necessary for the current resource. Subsequently, you may derive your “formula” of a universal template engine with a certain minimum set of functions, expanding as necessary in a single project.

It may seem that the author of this article is very skeptical of Smarty and other template engines. This is not true. For quite some time I worked with a project in which the same Smarty performed the role of a template engine. And I want to note, I really liked the use of this template system in the context of a project that is extensive in functionality.

But back to the gap between the visual and the abstraction. What are the minimum requirements a template engine should meet in an average project?
  • Ability to assign variables to a template
  • Separate variable namespace for a single html template
  • Ability to use one template for the general frame of the page to avoid repeating constructions of the form require 'header.tpl'; ... require 'footer.tpl'; in each file

By the way, the “average” project is a certain standard of measuring the complexity of a web application on my personal scale and meets approximately the following criteria:
  • A project is an online store or social community.
  • 10-20 types of pages. I emphasize - NOT pages, but page types. For example: product description page. Those. There will be one html-template for this type of page, but there will be many pages themselves when the directory is filled with content

Each developer has this own scale, so please do not judge strictly in this matter.

Let's move from words to deeds.

Consider the simplest class, which consists of only three methods.

_tmpl = $filename;
    }
    public function assign($name, $value) {
        $this->_vars[$name] = $value;
    }
    public function render() {
        if (count($this->_vars) > 0) {
            extract($this->_vars);
        }
        $tmplPath = "../templates/{$this->_tmpl}.tpl";
        if (file_exists($tmplPath)) {
            require $tmplPath;
        } else {
            throw new Exception("Шаблон {$this->_tmpl} не найден");
        }
    }
}


Let's look at an example using this class. Create the following directory structure:

/ wwwroot
|
- / classes
| - Template.php
- / templates
| - Main.tpl
| - Catalog.tpl
| - Product.tpl
| - Index.tpl
| - 404.tpl
| - index.php

Main.tpl


Catalog.tpl

Каталог №



Product.tpl

Страница описания продукта №



Index.tpl

Это главная страница сайта



404.tpl

Страница не найдена!



index.php
/**
 * Буферизация вывода.
 * Все, что будет выводиться echo-м или print-ом, будет попадать в буфер, а не в браузер пользователю.
  */
ob_start();
// Подключаем шаблонизатор
require dirname(__FILE__).'/classes/Template.php';
// Производим проверку маршрутизации и включаем необходимые шаблоны
// Если не один из шаблонов не найден, отправляем клиенту код ошибки и показываем шаблон 404.tpl
// Если маршрут не задан, выводим главную страницу
if (isset($_GET['route']) && $_GET['route'] == 'catalog') {
    $tmpl = new Template('Catalog');
    $tmpl->assign('ID', $_GET['ID']);
    $tmpl->render();
} else if ($_GET['route']) && $_GET['route'] == 'product') {
    $tmpl = new Template('Catalog');
    $tmpl->assign('ID', $_GET['ID']);
    $tmpl->render();
} else if (!isset($_GET['route'])) {
    $tmpl = new Template('Index');
    $tmpl->render();
} else {
    header("HTTP/1.0 404 Not Found");
    $tmpl = new Template('404');
    $tmpl->render();
}
// Получаем содержимое буфера
$content = ob_get_clean();
// Инициализируем шаблон каркаса страницы и выводим ранее сгенерированное содержимое
$tmpl = new Template('Main');
$tmpl->assign('content', $content);
$tmpl->render();


As you can see from the example, the contents of the catalog and product pages change depending on the value of $ _GET ['ID']. T.O. we got two types of templates and an unlimited number of pages generated by the application from these templates.

Conclusion: do not strive in all the projects that you are engaged in to use sophisticated template libraries that provide a large abundance of all kinds of tools, which in most cases are not used to the proper extent. It’s best to write your own solution, which will save time, system resources, and most importantly - the nerves will remain in order.

Thanks for attention.

Also popular now: