Template Engines
To better understand the foundations of template engines it is best to start by clarifying what they are and what they do. What do projects benefit from using them and how do they affect projects, from the system design to its maintainability.
What is a template engine?
A template engine is a piece of software designed to combine a template with data in order to produce content. A template is an intermediate representation of the content. It specifies rules defining on how the output will be generated.
Let's take a look to one of the simplest template engines - the Java native String.format
.
String.format("Hello, I am %d years old", 30);
Yes, String.format can be seen as a template engine, a really simple one. In the previous example, the data is the integer 30
which, when combined with the template Hello, I am %d years old
, generates the output Hello, I am 30 years old
.
Why template engines?
Because they optimize the process of producing content by, mainly, avoiding repetition. In essence, a template engine allows one to reuse the same template with different data generating therefore different content. It splits the data from its presentation, allowing to develop the presentation and logic layer almost independently, where the only dependency is the data (also named data model).
Splitting this layers eases maintenance by increasing the application modularity and changeability. For example, during the initial stages of a project, both layers might have similar change rates, however, when the project enters the maintenance mode, the presentation layer tends to be more subject to change. Without a template engine, it would be required logic layer changes in order to affect the presentation.
Another reason to adopt template engines, as tools written specifically for presentation logic development, it is because they simplify the development by providing several useful functionalities.
Why Jtwig?
Jtwig appears from the desire of a better template engine in the Java world. After investigating all technologies available in the market, one decided to, instead of creating a brand new technology, port one good template engine to the Java world, mainly because one could only benefit from an already mature technology, heavily used and proven in the wild. Twig which is based on Django templates itself, was the choice. It was seen as the best alternative given the following arguments:
- Code island based syntax, making it easier to read when mixed with presentation content;
- Small learning curve, easy and common syntactic constructs, in fact, for Java developers, Jtwig represents a small deviation from Java syntax;
- Simple yet powerful modularization mechanism;
- Great expressive power with the capability to create logical complex templates;