Jump to content

Building a flexible template system with Twig - Part 1: Extendible template structures


MoritzLost
 Share

Recommended Posts

I have recently started to integrate Twig in my ProcessWire projects to have a better separation between logic and views as well as have cleaner, smaller template files as opposed to large multi-purpose PHP-templates. Though there is a Twig module, I have opted to initialize twig manually to have more control over the structure and settings of the twig environment. This is certainly not required to get started, but I find that having no "secret sauce" gives the me as a developer more agency over my code structure, and better insights into how the internals of the libraries I'm using work.

Framework like Drupal or Craft have their own Twig integration, which comes with some opinionated standards on how to organize your templates. Since Twig is not native to ProcessWire, integrating Twig requires one to build a solid template structure to be able to keep adding pages and partials without repeating oneself or having templates grow to unwieldy proportions. This will be an (opinionated) guide on how to organize your own flexible, extensible template system with ProcessWire and Twig, based on the system I developed for some projects at work.

Somehow this post got way too long, so I'm splitting it in two parts. I will cover the following topics:

  1. Part 1: Extendible template structures
    • How to initialize a custom twig environment and integrate it into ProcessWire
    • How to build an extendible base template for pages, and overwrite it for different ProcessWire templates with custom layouts and logic
    • How to build custom section templates based on layout regions and Repeater Matrix content sections
  2. Part 2: Custom functionality and integrations
    • How to customize and add functionality to the twig environment
    • How to bundle your custom functionality into a reusable library
    • Thoughts on handling translations
    • A drop-in template & functions for responsive images as a bonus

However, I will not include a general introduction to the Twig language. If you are unfamiliar with Twig, read the Twig guide for Template Designers and Twig for Developers and then come back to this tutorial.

That's a lot of stuff, so let's get started ?

Initializing the Twig environment

First, we need to install Twig. If you set up your site as described in my tutorial on setting up Composer, you can simply install it as a dependency:

composer require "twig/twig:^2.0"

I'll initialize the twig environment inside a prependTemplateFile and call the main render function inside the appendTemplateFile. You can use this in your config.php:

$config->prependTemplateFile = '_init.php';
$config->appendTemplateFile = '_main.php';

Twig needs two things: A FilesystemLoader to load the templates and an Environment to render them. The FilesystemLoader needs the path to the twig template folder. I'll put my templates inside site/twig:

$twig_main_dir = $config->paths->site . 'twig';
$twig_loader = new \Twig\Loader\FilesystemLoader($twig_main_dir);

As for the environment, there are a few options to consider:

$twig_env = new \Twig\Environment(
    $twig_loader,
    [
        'cache' => $config->paths->cache . 'twig',
        'debug' => $config->debug,
        'auto_reload' => $config->debug,
        'strict_variables' => false,
        'autoescape' => true,
    ]
);
if ($config->debug) {
		$twig_env->addExtension(new \Twig\Extension\DebugExtension());
}
  • Make sure to include a cache directory, or twig can't cache the compiled templates.
  • The development settings (debug, auto_reload) will be dependent on the ProcessWire debug mode.
  • I turned strict_variables off, since it's easier to check for non-existing and non-empty fields with some parts of the ProcessWire API.
  • You need to decide on an escaping strategy. You can either use the autoescape function of twig, or use textformatters to filter out HTML tags (you can't use both, as it will double escape entities, which will result in a broken frontend). I'm using twig's inbuilt autoescaping, as it's more secure and I don't have to add the HTML entities filter for every single field. This means pretty much no field should use any entity encoding textformatter.
  • I also added the Debug Extension when $config->debug is active. This way, you can use the dump function, which makes debugging templates much easier.

Now, all that's left is to add a few handy global variables that all templates will have access to, and initialize an empty array to hold additional variables defined by the individual ProcessWire templates.

// add the most important fuel variables to the environment
foreach (['page', 'pages', 'config', 'user', 'languages', 'sanitizer'] as $variable) {
    $twig_env->addGlobal($variable, wire($variable));
};
$twig_env->addGlobal('homepage', $pages->get('/'));
$twig_env->addGlobal('settings', $pages->get('/site-settings/'));

// each template can add custom variables to this, it
// will be passed down to the page template
$variables = [];

This includes most common fuel variables from ProcessWire, but not all of them. You could also just iterate over all fuel variables and add them all, but I prefer to include only those I will actually need in my templates. The "settings" variable I'm including is simply one page that holds a couple of common settings specific to the site, such as the site logo and site name.

Page templates

By default, ProcessWire loads a PHP file in the site/templates folder with the same name of the template of the current page; so for a project template/page, that would be site/templates/project.php. In this setup, those files will only include logic and preprocessing that is required for the current page, while the Twig templates will be responsible for actually rendering the markup. We'll get back to the PHP template file later, but for the moment, it can be empty (it just needs to exist, otherwise ProcessWire won't load the page at all).

For our main template, we want to have a base html skeleton that all sites inherit, as well as multiple default regions (header, navigation, content, footer, ...) that each template can overwrite as needed. I'll make heavy use of block inheritance for this, so make sure you understand how that works in twig.

For example, here's a simplified version of the html skeleton I used for a recent project:

{# site/twig/pages/page.twig #}

<!doctype html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{{ '%s | %s'|format(page.get('title'), homepage.title) }}{% endblock %}</title>
    <link rel="stylesheet" type="text/css" href="{{ config.urls.site }}css/main.css">
</head>
<body class="{{ page.template }}">
    {% block navigation %}{{ include("components/navigation.twig") }}{% endblock %}
	
    {% block header %}{{ include("components/header.twig") }}{% endblock %}
	
    {% block before_content %}{% endblock %}
	
    {% block content %}
        {# Default content #}
    {% endblock %}
	
    {% block after_content %}{% endblock %}
	
    {% block footer %}{{ include("components/footer.twig") }}{% endblock %}
</body>
</html>

All layout regions are defined as twig blocks, so each page template can override them individually, without having to touch those it doesn't need. I'll fill the content block with default content soon, but for now this will do. Now, templates for our content types can just extend this base. This is the template for the homepage:

{# site/twig/templates/pages/page--home.twig #}

{% extends "pages/page.twig" %}

{# No pipe-seperated site name on the homepage #}
{% block title page.get('title') %}

{# The default header isn't used on the homepage #}
{% block header %}{% endblock %}

{# The homepage has a custom slider instead of the normal header #}
{% block before_content %}
    {{ include('sections/section--homepage-slider.twig', { classes: ['section--homepage-slider'] }) }}
{% endblock %}

Note that I don't do most of the actual html markup in the page templates, but in individual section templates (e.g. section--homepage-slider.twig) that can be reused across content types. More on this in the next section.

We still need to actually render the template. The page template (which will be the entry point for twig) will be loaded in our _main.php, which we defined as the appendTemplateFile earlier, so it will always be included after the template specific PHP file.

$template_file = 'pages/page--' . $page->template->name . '.twig';
$twig_template = file_exists($twig_main_dir . '/' . $template_file)
    ? $template_file
    : 'pages/page.twig';
echo $twig_env->render($twig_template, $variables);

This function checks if a specific template for the current content type exists (e.g. pages/page--home.twig) and falls back to the default page template if it doesn't (e.g. pages/page.twig). This way, if you want a blank slate for a specific content type, you can just write a twig template that doesn't extend page.twig, and you will get a blank page ready to be filled with whatever you want.

Note that it passes the $variables we initialized in the _init.php. This way, if you need to do any preprocessing or data crunching for this request, you can do it inside the PHP template and include the results in the $variables array.

At this point, you can start building your default components (header, footer, navigation, et c.) and they will be included on every site that extends the base page template.

Custom sections

Now we've done a great deal of setup but haven't actually written much markup yet. But now that we have a solid foundation, we can add layout components very easily. For most of my projects, I use the brilliant Repeater Matrix module to set up dynamic content sections / blocks (this is not the focus of this tutorial, here's a detailed explanation). The module does have it's own built-in template file structure to render it's blocks, but since it won't work with my Twig setup, I'll create some custom twig templates for this. The approach will be the same as with the page template itself: create a "base" section template that includes some boilerplate HTML for recurring markup (such as a container element to wrap the section content in) and defines sections that can be overwritted by section-specific templates. First, let's create a template that will iterate over our the Repeater Matrix field (here it's called sections) and include the relevant template for each repeater matrix type:

{# components/sections.twig #}

{% for section in page.sections %}
    {% set template = 'sections/section--' ~ section.type ~ '.twig' %}
    {{ 
        include(
            [template, 'sections/section.twig'],
            { section: section },
            with_context = false
        )
    }}
{% endfor %}

Note that the array syntax in the include function tells Twig to render the first template that exists. So for a section called downloads, it will look look for the template sections/section--downloads.twig and fallback to the generic sections/section.twig. The generic section template will only include the fields that are common to all sections. In my case, each section will have a headline (section_headline) and a select field to choose a background colour (section_background) :

{# sections/section.twig #}

{% set section_classes = [
    'section',
    section.type ? 'section--' ~ section.type,
    section.section_background.first.value ? 'section--' ~ section.section_background.first.value
] %}

<div class="{{ section_classes|join(' ')|trim }}">
    <section class="container">
        {% block section_headline %}
            {% if section.section_headline %}
                <h2 class="section__headline">{{ section.section_headline }}</h2>
            {% endif %}
        {% endblock %}
        {% block section_content %}
            {{ section.type }}
        {% endblock %}
    </section>
</div>

This section template generates classes based on the section type and background colour (for example: section section--downloads section--green) so that I can add corresponding styling with CSS / SASS. The specific templates for each section will extend this base template and fill the block section_content with their custom markup. For example, for our downloads section (assuming it contains a multivalue files field download_files):

{# sections/section--download.twig #}

{% extends "sections/section.twig" %}

{% block section_content %}
    <ul class="downloads">
        {% for download in section.download_files %}
            <li class="downloads__row">
                <a href="{{ download.file.url }}" download class="downloads__link">
                    {{ download.description ?: download.basename }}
                </a>
            </li>
        {% endfor %}
    </ul>
{% endblock %}

It took some setup, but now every section needs only care about their own unique fields and markup without having to include repetitive boilerplate markup. And it's still completely extensible: If you need, for example, a full-width block, you can just not extend the base section template and get a clean slate. Also, you can always go back to the base template and add more blocks as needed, without having to touch all the other sections. By the way, you can also extend the base section template from everywhere you want, not only from repeater matrix types.

Now we only need to include the sections component inside the page template

{# pages/page.twig #}

{% block content %}
    {% if page.hasField('sections') and page.sections.count %}
        {{ include('components/sections.twig' }}
    {% endif %}
{% endblock %}

Conclusion

This first part was mostly about a clean environment setup and template structure. By now you've probably got a good grasp on how I organize my twig templates into folders, depending on their role and importance:

  • blocks: This contains reusable blocks that will be included many times, such as a responsive image block or a link block.
  • components: This contains special regions such as the header and footer that will probably be only used once per page.
  • sections: This will contain reusable, self-contained sections mostly based on the Repeater Matrix types. They may be used multiple times on one page.
  • pages: High-level templates corresponding to ProcessWire templates. Those contain very little markup, but mostly include the appropriate components and sections.

Depending on the size of the project, you could increase or decrease the granularity of this as needed, for example by grouping the sections into different subfolders. But it's a solid start for most medium-sized projects I tackle.

Anyway, thanks for reading! I'll post the next part in a couple of days, where I will go over how to add more functionality into your environment in a scalable and reusable way. In the meantime, let me know how you would improve this setup!

  • Like 8
  • Thanks 5
Link to comment
Share on other sites

Thank you very much for this starting tutorial!

I love to work with Twig. I am switching over from OctoberCMS to Processwire and it is hard to get over from Twig template files to a plain PHP.

So I am happy to have a starting point to start working with Twig in my Processwire Projects.

Greetings from Austria to Germany

  • Like 1
Link to comment
Share on other sites

  • 4 weeks later...

This is terrific.  Even better would be to build Twig into the core, and allow .twig and .php.  I'm a huge Symfony fan, and miss the tools there.

It's hard to go back to PHP templates once you've gotten used to Twig.  PHPStorm now even support debugging twig templates!

  • Like 1
Link to comment
Share on other sites

  • 3 weeks later...

I've obviously missed something, because I'm getting Call to a member function render() on null from _main.php. My templates are…

_init.php

<?php

$twig_main_dir = $config->paths->site . 'templates/views';
$twig_loader = new \Twig\Loader\FilesystemLoader($twig_main_dir);

$twig_env = new \Twig\Environment(
	$twig_loader,
	[
		'cache' => $config->paths->cache . 'twig',
		'debug' => $config->debug,
		'auto_reload' => $config->debug,
		'strict_variables' => false,
		'autoescape' => true,
	]
);
if ($config->debug) {
	$twig_env->addExtension(new \Twig\Extension\DebugExtension());
}

foreach (['page', 'pages', 'config', 'user', 'languages', 'sanitizer'] as $variable) {
	$twig_env->addGlobal($variable, wire($variable));
};
$twig_env->addGlobal('homepage', $pages->get('/'));
$twig_env->addGlobal('settings', $pages->get('/site-settings/'));

$variables = [];

_main.php

<?php

$template_file = 'views/' . $page->template->name . '.twig';
$twig_template = file_exists($twig_main_dir . '/' . $template_file)
    ? $template_file
    : 'views/basic-page.twig';
echo $config->twig_env->render($twig_template, $variables);

My .twig templates are set up as yours are and my PW .php templates are just blank at the moment.

  • Like 1
Link to comment
Share on other sites

@Tyssen, it looks like the original examples had a small mistake – either that, or I'm missing something as well. You should either store $twig_env in $config in your _init.php file, or (more likely) call it directly with $twig_env in _main.php ?

  • Like 2
Link to comment
Share on other sites

8 hours ago, teppo said:

@Tyssen, it looks like the original examples had a small mistake – either that, or I'm missing something as well. You should either store $twig_env in $config in your _init.php file, or (more likely) call it directly with $twig_env in _main.php ?

@Tyssen @teppo Yeah that was a mistake, sorry about that. I always add the twig instances to the config to be able to access them globally, but here I didn't include that part. I corrected it in the OP!

7 hours ago, Tyssen said:

Another question: in Twig how would you call modules like AIOM where in PHP it'd be <?=AIOM:CSS(array())?> or <?=AIOM:JS(array())?> ?

Actually never mind, set it as a variable in _init.php and then call it in the twig template.

Yeah, I think setting the output as a variable in the _init.php or _main.php is the best option here, since you can't directly call static methods of classes in twig. Another option, if it's a method you need to access more often, is to write a wrapper twig function and add it to your twig environment. There are some example for this in the second part of the tutorial - let me know if it's not working for you!

  • Like 1
Link to comment
Share on other sites

  • 7 months later...

Nice work!

I made a Twig module way back as I was doing similar things to what you do here. Since then others have made (far cleaner) Twig modules too and I recommend these for most people. Getting your hands dirty and seeing how relatively straight-forward it is to use Twig or similar engines from scratch with ProcessWire is extremely valuable though - even if you go back to using the modules in the end. It gives a much clearer picture of what is going on (and therefore what could go wrong too).

I've started playing with the Latte templating engine recently and love it (though I hate Php's $ style variables and -> style object notations which Latte uses), but Twig will always hold a special place as it was the first templating engine that actually felt good to use and not a chore!

Thanks for the great tutorial!

  • Like 1
Link to comment
Share on other sites

  • 2 months later...

Even though I dove into this nearly a year ago on my local dev server, I never actually got around to using it on a production site until now. And now when I try to run on the live server I get:

Quote

Class 'Twig\Loader\FilesystemLoader' not found

File: .../public_html/site/templates/_init.php:4
$twig_main_dir = $config->paths->site . 'templates/';
$twig_loader = new \Twig\Loader\FilesystemLoader($twig_main_dir);

Any ideas what I need to do to clear up that error? I've run `composer update` on the server and also `composer dump-autoload`.

Link to comment
Share on other sites

8 hours ago, Tyssen said:

Even though I dove into this nearly a year ago on my local dev server, I never actually got around to using it on a production site until now. And now when I try to run on the live server I get:


File: .../public_html/site/templates/_init.php:4
$twig_main_dir = $config->paths->site . 'templates/';
$twig_loader = new \Twig\Loader\FilesystemLoader($twig_main_dir);

Any ideas what I need to do to clear up that error? I've run `composer update` on the server and also `composer dump-autoload`.

If the class can't be found, the autoloader probably hasn't been included for some reason.

  1. Where are you including the autoloader? Make sure it's loaded before using the Twig classes: var_dump(class_exists('Twig\Loader\FilesystemLoader'));
    If it doesn't, the autoloader likely hasn't been included yet, or Twig is not installed.
  2. Which version Twig are you using? If you're using an older version of Twig 1, the namespaced classes may not exist in your version yet. In that case try to update to the latest 2.X or 3.X version.
  3. Have you made sure that the composer.json on your live server actually includes the Twig requirement?
Link to comment
Share on other sites

Don't you hate it when the answer to the problem turns out to be really stupid? I had `require '../vendor/autoload.php'` in config-dev.php so it was working fine locally but not in config.php on the server. ?

  • Like 1
Link to comment
Share on other sites

  • 3 weeks later...

I have a repeater matrix field on a page and one of the matrix types has an options fieldtype. If I do {{ matrixBlock.fieldName }} I get the numeric value of the selected option. But if I do {{ matrixBlock.fieldName.value }} (or title) I get:

Quote

Fatal Error: Uncaught ArgumentCountError: Too few arguments to function ProcessWire\SelectableOptionArray::hasValue(), 0 passed in /vendor/twig/twig/src/Extension/CoreExtension.php on line 1499 and exactly 1 expected in /public_html/wire/modules/Fieldtype/FieldtypeOptions/SelectableOptionArray.php:226

Any ideas?

  • Like 1
Link to comment
Share on other sites

@Tyssen I've run into that error a couple of times, I think it's specific to the Selectable Option field. I think it's related to how Twig tries different ways to get a property value from an object. ProcessWire uses magic __get methods all over the place, which are checked quite late by Twig. So Twig first tries to call hasValue on the object, which exists but requires additional arguments, so it breaks ...

A workaround is using more explicit properties, either of those should work:

{{ matrixBlock.fieldName.getValue }}
{{ matrixBlock.fieldName.first.value }}

 

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...