Building a Template System for Your PHP Application.

Paweł Mikołajczuk
2 min readMay 30, 2017

--

Today I would like to present you with a solution which my team of developers from Sourcefabric came up with in order to allow fetching of either a single article or article list and place it in any website page (frontpage, article page, section page etc.) in an easy and flexible way.

Background: Superdesk Publisher is the software that we are currently developing. It is built on PHP7 and uses TWIG as a template engine. For the themes management we use Sylius Theme Bundle.

Based on previous experiences in the development of CMSs, one of the goals we set was to provide an easy-to-work-with system for templators unfamiliar with PHP. Therefore, the solution developed for listing and fetching different content items like: articles, routes, article media, image renditions, content list items and more, is very easy and intuitive.

Keeping in mind that our first choice was TWIG for the templates, we decided to extend its DSL.

We introduced two custom twig nodes:

  • gimme (for fetching a single META)
  • gimmelist (for fetching a collection of META’s).

What’s META?

Meta objects provides an extra layer between your internal documents/entities and this what’s available for theme developer (templator). Thanks to this feature you can make more changes in your project code and data structures without breaking the templates. (docs)

Let’s see the syntax of those nodes.

{% gimme article with { articleNumber: 1 } %}
{# Meta Loader will use provided parameters to load article Meta #}
{{ article.title }}
{% endgimme %}

Gimme allows you to load a single META object from the Loader (read more about loaders here). You can provide custom parameters to the loader (with { articleNumber: 1}).

{% gimmelist article from articles|start(0)|limit(10)|order('id', 'desc')
with {foo: 'bar', param1: 'value1'}
contextIgnore ['route', 'article']
if article.title == "New Article 1"
%}
{{ article.title }}
{% endgimmelist %}

Gimmelist is more powerful. Collection Loader allows you to manipulate pagination with thestart and limit filters and change an item’s order with the order filter. Node behaves as a loop and you have access to all TWIGfor loop properties.

Full documentation can be found here: http://superdesk-publisher.readthedocs.io/en/latest/manual/templates_system/templates_features.html.

See Superdesk Publisher Bundles and Components here: https://github.com/superdesk/web-publisher#superdesk-publisher-is-possible-thanks-to-other-sourcefabric-initiatives

--

--

Paweł Mikołajczuk

Open Source developer (#php, #javascript). Focused on software for newsrooms. Github: https://github.com/ahilles107