The Power of Templating Engines – Boston WordCamp 2016 Presentation

Php has practically built the web. It is a versatile language, but there is not much to prevent you from writing really messy code. Therefore, it has a bad rap in some circles. Over the years, members of the php community have built some great tools to help prevent developers become not only more efficient, but also better coders. One such tool is that of templating engines. Although the primary function of a templating engine is to force you into separating your concerns, there are several other important features that they provide.

Separation of Concerns

Separation of Concerns is easy to violate when working with WordPress. Even if you are an experienced programmer, it is easy to get lazy and mix business logic with view logic. Hence, templating engines seek to prevent you, the programmer from violating separation of concerns.

WikiPedia defines separation of concerns as:

In computer science, separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. A concern is a set of information that affects the code of a computer program.

What you really need to understand as a developer is that business logic should be separate from your views and view logic.

Business Logic

Business logic is what happens behind the scenes such as validating a form, processing data, or checking if a user is actually logged in. It is also CRUD( creating, reading, updating, and destroying data).

View Logic

The view is what gets displayed to the user. This is, therefore the HTML and CSS. The view logic is any logic that is essential to rendering the view. For example, if you are rendering a list of books and you want the title of books by “author a” to be blue and titles by any other author would be in red. In this case, because this logic relates to display, it would be acceptable to put this logic in the view.

WordPress and separation of concerns

WordPress Business Logic is handled by WordPress Core and Posts

In theory “Posts” and “site options” represent most data in WordPress. WordPress core is responsible for the business logic, which means that it handles saving the data etc, redirects, etc. WordPress core can be extended through plugins, of course.

WordPress Views and View Logic are handled by the theme

Your theme is responsible for handling the view and view logic. Within the theme are the template files. “page.php”, “sidebar.php”, “single.php” are all template files. These files, as a result are where our html is rendered.

"WordPress

Templating Engines

Templating engines exist primarilly to make sure that you the programmer do not violate separation of concerns. In addition, they also have some other very nice features that help you write cleaner, more efficient code. There are many options available for both Javascript and Php. The infographics below illustrate several of the more popular options for each language.

[cherry_row]
[cherry_col size_md=”6″]popular php templating engines[/cherry_col]
[cherry_col size_md=”6″]popular javascript templating engines
[/cherry_col]
[/cherry_row]

This article will focus primarily on the options available for php. However Javascript templating engines work in the same way.

Templating Engine Benefits

Enforce Separation of Concerns

In most cases, if you violate separation of concerns, you will raise an error. For example, you can’t declare or modify variables, call superglobal variables such as $_POST, or call a function. In some cases such as Twig, you can extend it to allow a specific function to be called.

The following examples would raise an error in most templating engines.

[sourcecode lang=”php” htmlscript=”true” light=”true” theme=”default”]
<?php $name="Dan"; ?>
[/sourcecode]

[sourcecode lang=”php” htmlscript=”true” light=”true”]
<p><?php echo $_POST[‘fName’]; ?></p>
[/sourcecode]

[sourcecode lang=”php” htmlscript=”true” light=”true”]
<p><?php echo someFunction(); ?></p>
[/sourcecode]

Therefore, the correct way to use any of the above snippets is to process the data first and then pass it into the template file. See example below.

[php]

/**
* buslogic.php
* This is a generic example but the process is the same no matter which engine you are using. The idea is that
* The business logic is done on the php side and then passed into the template file. If you do not pass your
* data in this manner, an error will be triggered. Each engine would have a different extension. For example
* twig is .twig, blade is .blade.php, smarty is .tpl.
**/

$context[‘name’] = ‘Dan’;
$context[‘fName’] = $_POST[‘fName’];
$context[‘func’] = someFunction();

$template = TemplateEngine::render(‘template.eng’, $context);

[/php]

As a result, we have effectively separated our business logic from our view logic. Therefore we can focus on the markup in our view.

Cleaner Syntax

Templating engines provide different and arguably cleaner syntax. Each templating engine has its own unique syntax. As a result, most modern templating engines in php do not use “open” and “close” php tags.

Printing Variables

[php]
//twig
//notice twig removes the "$"
{{ var }}
[/php]

[php]
//blade
{{ $var }}
[/php]

[php]
//smarty
{ $var }
[/php]

[php]
//HAML
= $var
[/php]

[php]
//Moustache

{{ var }}
[/php]

Block Syntax

[php]

//twig
{% for item in items %}
{% if item %}
//do stuff
{% endif %}
{% endfor %}

[/php]

[php]

//blade
@foreach ($items as $item)
@ if ( $item )
//do stuff
@endif
@endforeach

[/php]

[php]
//Smarty
{foreach from=$items item=item}
{if $item }
//do stuff
{/if}
{/foreach}

[/php]

[php]
//HAML
– foreach ($items as $item)
– if $item
//do stuff

[/php]

[php]
/**
* Moustache brands itself as being a "logicless" templating engine.
* This logic should be done outside of your template. That means there are no "if"
* statements allowed.
**/

{{#items}}
//do stuff here
{{/items}}
Template Inheritance
[/php]

Template Inheritance

Many templating engines provide a feature called “Template Inheritance.” This is very similar to the concept of class inheritance in object oriented programming (oop). In oop you have a parent class which you can extend with new functionality or override parent functions. With template inheritance, you have a base template that has certain areas, which you can override with a child template.

[sourcecode lang=”php” htmlscript=”true”]
/**
* This is the base template. Please note that this is done generically, but it resembles
* twig. Please refer to the documentation of your preferred engine to properly implement
* template inheritance.
**/
//base.tmpl

<html>
<head>
<title>Title Here</title>
</head>
<body>
{% section body %}
<p>This is our body. We can override this or inherit this section</p>
{% end section %}
</body>
</html>
[/sourcecode]

[sourcecode]
/**
* This is the child template. Please note that this is done generically, but it resembles
* twig. Please refer to the documentation of your preferred engine to properly implement
* template inheritance.
**/
//child1.tmpl

{% section body %}
<p>This is the child.</p>
{% end section %}

[/sourcecode]

The child template would render the following html:

[sourcecode lang=”php” htmlscript=”true”]

<html>
<head>
<title>Title Here</title>
</head>
<body>
<p>This is the child.</p>
</body>
</html>
[/sourcecode]

It is also possible to inherit what is in the parent and then add on to it, instead of overriding.

[sourcecode]
/**
* This is the child template. Please note that this is done generically, but it resembles
* twig. Please refer to the documentation of your preferred engine to properly implement
* template inheritance.
**/
//child1.tmpl

{% section body %}
{{ parent() }}
<p>This is the child.</p>
{% end section %}

[/sourcecode]

This child template would render the following html:

[sourcecode lang=”php” htmlscript=”true”]

<html>
<head>
<title>Title Here</title>
</head>
<body>
<p>This is our body. We can override this or inherit this section</p>
<p>This is the child.</p>
</body>
</html>
[/sourcecode]

As you can see, it took what was in the parent’s body, and rendered that in addition to the html that was in the child’s body.

Conclusion

Picking a good templating engine can help your workflow and help you write better code by forcing you to separate your concerns. When you write your code in this manner, it will be much easier to work in teams and write testable and maintainable code that scales well. Consider using a templating engine in your next project. I’m pretty sure you will be quite happy with the results!