Guide to Templating and Structured Content in Sulu

Every website project requires templating. In this guide we give you an overview how it works in Sulu. Find out how to use XML templates to set up the admin interface, why Sulu gives you more frontend freedom than other CMSs, and first steps to set you off on your way to satisfied developers, content editors, and end users.

Separating content from presentation

At the core of modern content management systems is a simple concept: the separation of content and presentation. In most enterprise CMSs, editors get to add and edit content, and it’s up to designers and developers to decide where and how it’s presented. It’s when editors start making presentation decisions that the problems start:

  • Different editors make different design decisions according to personal taste, leading to brand inconsistency.
  • Editors forget that their content is output on any number of devices from responsive websites to internet of things devices; via smart speakers; not just their computer.
  • Inconsistent content is less machine-readable, making it difficult to optimize assets for performance purposes.

At the same time, editors need to feel supported and in control, not held back. It’s possible to give them many options as long as they are well thought through.

Most CMSs have a database that stores the content, an editor interface for that content to be input, modified, and deleted; and a templating system for serving HTML generated from the content. Different CMSs are more or less rigorous in their approach.

Maximum freedom for developers

But even CMSs that successfully separate content and presentation can tie down developers by limiting their freedom to decide which frontend technology stack to use. Sulu, however, is built from the ground up on the Symfony framework. We reuse Symfony components whenever possible, and only implement necessary features that don’t exist already. We use the Twig frontend templating language, and leave frontend developers to choose whatever technology they want. So for Symfony backend developers, and all frontend developers, Sulu offers maximum freedom. The day-to-day benefit is best captured in a quote from one of our users, Jordy Groote:

Thanks to the speed of configuring templates, and setting up the CMS, we can teach frontenders to set up XML files for blocks and pages, so the backenders can focus on PHP code and the business logic.

Jordy Groote
Backend Developer – Triggerfish

How some CMSs mix content management with presentation

While Sulu was built on Symfony and Twig right from the beginning, other CMSs are racing to catch up. Many of them are refactoring their entire systems to use as much of the Symfony PHP framework as possible because they see the benefits of opening up to the wider PHP community. However, they still tie frontend developers to their own, idiosyncratic technologies such as non-standard templating languages that don’t work with other systems, and outdated or specific versions of JavaScript frameworks. Experienced developers can’t bring their full skill set immediately to bear when they have to learn a new system first! Some of these problems might sound familiar. Non-standard technologies cause:

  • A steep learning curve for frontend developers to learn a CMS-specific templating language
  • Creative limitations due to idiosyncrasies of a legacy templating system
  • Page bloat with unnecessary markup injected into templates from a base system
  • Delays while waiting for third-party libraries to get updated or integrated into a core system

With Sulu, the template definition has two parts. Both are written in code, which gives both content editors and developers many advantages. How does this compare to your experience with other systems?

  • In some systems, you don’t have complete control over the content editing UI. With Sulu, you can structure the forms editors use to enter content however you like, making it much more intuitive for editors.
  • Some systems define custom content types or data models in a UI. In Sulu, the way data is displayed is all handled in the frontend, which leads to less confusion. It’s all stored in files, not the database, which saves many a deployment headache.

Ah, but what about headless architecture?

Most CMSs are at least capable of operating in headless or decoupled mode, whereby you access the content directly and bypass the rendering engine. But then you don’t have a rendering engine at all. Some people do this because they want more control over their frontend technology, but this means effectively building your own rendering engine. With Sulu, you don’t have to throw out the rendering engine and build your own in order to have more control over your frontend technology — apart from the Twig templating language, Sulu lets you choose your stack. Read the article on using Sulu as a headless or decoupled CMS if you’re interested to learn more.

Sulu is a blank canvas for frontend developers

With Sulu, you’re free to do it your way. It’s a blank canvas, whereby you can access content and data through the Twig templating language, or output it to JSON and go from there. Admittedly, this can be daunting because you might not know where to start, especially if you’re used to installing a CMS or DXP and seeing default content when you open it in your browser for the first time. We feel that this strikes the right balance. Sulu comes with lots of standard functionality such as a fully working rendering engine, and the Sulu community is here to help on Slack.

One Sulu user commented that they liked the focus on building business logic:

It’s great how easy it is to set up a simple website and keep focus on custom development instead of template development.

Michel Falke
Senior Developer – Webstores B.V.

Building your own templates lets you take full advantage of the frontend delivery technology of your choice, instead of spending time overriding defaults the system imposes on you. For a quick start, you can take advantage of our Services and Support. If you’re looking to do something quite simple, you can buy a pre-built HTML template.

Another advantage of bringing your own frontend technology stack is that you can keep up with the fast pace of change. Things are so fast-moving in this area, you really don’t need content management issues holding you back from installing security and feature updates, or moving to a more appropriate technology.

Don’t forget that you’re not limited to HTML. You can, for example, output XML, which is useful when building RSS feeds using Twig.

So now that we’re on the same page, let’s look at the steps you need to take to go from mock ups, to XML templates, to Twig and HTML output.

Things to decide before starting a Sulu project

The first step in a web project is to produce mock ups. At the very least, you need some wireframes before you start. You’ll also need to have thought about your information architecture. At this point, it’s time to reach for the (metaphorical) scalpel and start dissecting your design. For every section of your website, you need to choose the most suitable way of populating it with content. That could be:

  • Static content. These bits of content are written into the template itself, or in configuration only the developer can access. For example, the site title and logo. You very rarely need to change these, so it’s okay to need to contact a developer to alter them.
  • Dynamic content. Site administrators and content editors change these using the admin interface. It can be site-wide (editable in the settings, or another dedicated menu item), or specific to a particular page. For example, the names of menu items are dynamic and occur on every page where the navigation is visible. The text of a blog entry, however, is dynamic but appears only where the article is displayed.
  • Smart content. Custom content that is pulled together from dynamic content and displayed in a particular view. For example, a list of articles in a category page showing the featured images, heading, and an excerpt of text.

This is a basic overview of the categories you need to divide content into. For every element on the page, you need to ask yourself the question: “Where does this come from?” Is it a recurring piece of content across the site? Do you want your editors or admins to be able to change it in one place? Or is it unique content, such as a page or article?

Building your project with Sulu

Before we start, let’s get some terminology straight. In Sulu, two different types of template control two different things:

  • How data is modelled, input, and validated.
    • This is defined in an XML file, which tells the system how to build the data-entry form in the admin interface.
  • How content is displayed in the browser.
    • This is defined in Twig templates, which determine what the rendering engine outputs, usually HTML.

Where confusion may occur, we’ll refer explicitly to “XML templates” and “Twig templates.”

XML vs YAML vs JSON

In our recent community survey, we were asked why we chose XML instead of JSON or YAML. Beside the advantages XML has in our opinion, we chose XML simply because people in our team have used it in the past, and it gets the job done. Magnolia, for example, takes a similar approach but uses YAML. So while many roads lead to Rome, this was just the one we chose.

Help

While the concept of Twig and XML templates sound similar, and they do handle mostly the same data, Sulu goes to great lengths to separate the concerns of data modeling and display. A key part of Sulu’s architecture is the ability for your application to hand over data cleanly without content and presentation becoming entangled, opening up many possibilities including headless setups.

Blocks are one of the Sulu concepts that make this possible.

Blocks

Blocks are Sulu’s way of keeping content neatly separated so it can be recombined in any way. Instead of having a single text editor field with loads of formatting options and the ability to insert inline images, Sulu offers editors blocks, which have been predefined by the developer, based on the needs and information architecture of the site. Each block contains content types, which are fields such as date, text, media selection and so on.

If, for example, you want to offer an editor a standardized article format, you might build a template with a heading, subheading, and cover image, as well as standard metadata such as the URL. You can then offer a variety of blocks that the editor can choose from: an inline image could contain fields for a media selection, text overlay, and a dropdown with a limited selection of image border colors. A text block could include limited, standard formatting options, or none at all. You could offer a newsletter signup block with no configuration options whatsoever, or a block to insert a standardized “Contact us” text with a link to the contact page. 

The point is: all these things are standardized so your data remains structured and independent of any output format. You can keep things standard across the site, avoiding entering the same information over and over and giving you a single place to modify every occurrence centrally. All the while, your editors still have creative freedom to organize content as they wish.

Since Sulu 2.1, in response to many requests from developers, we made it possible to nest blocks. This is useful for offering container elements that can contain several blocks. For example, product pages may contain standardized blocks with a list of features, and each feature item needs to have standardized fields. If you don’t know in advance exactly how many features every product contains, you can enable the editor to add an arbitrary number of features to the feature block element.

At the weekend, I started building a website for a friend with Sulu. It was so much fun that I kept going until two in the morning on Saturday! Nested blocks are amazing. And generally I find it a thousand times easier as a (former) developer to build a website with Sulu and an HTML template than with WordPress or Joomla, for example.

Tobias Niebergall
Founder & COO – e3n GmbH & Co. KG

XML templates

In order for a content editor to have access to an input form and blocks, we need to tell Sulu:

  • What content types (form fields) the input form should contain.
  • What blocks are available, and what content types they contain.

This is what the XML template is for. The developer doesn’t have to write any PHP code, but instead gives Sulu the information it needs to generate standardized forms in the Sulu interface. This method is much faster, avoids boilerplate code, easier to maintain and update, and less error-prone than expecting the developer to write all the forms they need.

This method also has a big advantage over systems where site-builders can click forms together via a web interface. XML files are just that: files within the file system, and not configuration in the database. You can track and deploy them with the rest of your code in version-control systems like Git. It makes developers’ lives much easier and avoids many opportunities for human error or unintentional inconsistencies.

Let’s look at an example, first from the admin UI and output, and then the code. 

The image below illustrates how the content output (an article) is related to its input form.

The illustration shows the “Details” tab for content input. This form includes the following content types:

FormContent TypePurpose
Titletext_linePage heading.
Resource Locatorresource_locatorTo set a custom URL. Though Sulu will automatically create a URL based on the Title.
Image Gallerymedia_selectionWidget for selecting media, in this case, images.
Articletext_editorA multi-line field with a rich-text editor.

To create this form, we need an XML template for a simple input form for an article. The resulting form collects the data in the right format and validates user input.

<?xml version="1.0" ?>
<template xmlns="http://schemas.sulu.io/template/template"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://schemas.sulu.io/template/template http://schemas.sulu.io/template/template-1.0.xsd">

    <key>default</key>

    <view>pages/default</view>
    <controller>Sulu\Bundle\WebsiteBundle\Controller\DefaultController::indexAction</controller>
    <cacheLifetime>604800</cacheLifetime>

    <meta>
        <title lang="en">Default</title>
        <title lang="de">Standard</title>
    </meta>

    <properties>
        <property name="title" type="text_line" mandatory="true">
            <meta>
                <title lang="en">Title</title>
                <title lang="de">Titel</title>
            </meta>
            <params>
                <param name="headline" value="true"/>
            </params>

            <tag name="sulu.rlp.part"/>
        </property>

        <property name="url" type="resource_locator" mandatory="true">
            <meta>
                <title lang="en">Resource Locator</title>
                <title lang="de">Adresse</title>
            </meta>

            <tag name="sulu.rlp"/>
        </property>

        <property name="gallery" type="media_selection">
            <meta>
                <title lang="en">Image Gallery</title>
                <title lang="de">Bildergalerie</title>
            </meta>
        </property>

        <property name="article" type="text_editor">
            <meta>
                <title lang="en">Article</title>
                <title lang="de">Artikel</title>
            </meta>
        </property>

    </properties>
</template>
XML templates

Twig templates

Twig is the standard Symfony templating language. It’s widely adopted and well documented. We feel there’s no need for us to make our own templating language.

Twig templates contain no PHP code. You write your HTML, and output data into the right places. There are some functions for looping over arrays and the like, and some filters for determining how data is output, but all business logic and data processing is done in the backend. This is more secure than having PHP in frontend templates.

Here’s an extract from a Twig template as an example. It’s tidy and clear, and it’s easy for a reader to distinguish between HTML and the Twig placeholders.

 

{% extends "base.html.twig" %}
​
{% block content %}
    <h1>{{ content.title }}</h1>
​
    <div class="gallery">
        {% for image in content.gallery %}
            <img src="{{ asset(image.thumbnails['1024x480']) }}" alt="{{ image.title }}"/>
        {% endfor %}
    </div>
​
    <div class="article">
        {{ content.article|raw }}
    </div>
{% endblock %}
Twig template

This part of the application deals with what other CMSs sometimes refer to as “theming.” You can think of it as the skin in which the data is presented. In Sulu, the strict separation between content and presentation means you can display the same page in two different places and make it look entirely different: the same piece of content can appear in different Workspaces with a different Twig template.

Sulu has a useful live preview function for editors. While the content editor interface is purposely not WYSIWYG, editors can preview what their content would look like in a web browser on desktop, tablet and mobile.

Best practices

That’s about it! One of the beauties of working with Sulu is that you get a blank canvas to build your frontend from scratch — as many frontends and channels as you need from the data and business logic. You can find more details for developers in our documentation: Creating a Page Template.

In terms of tips and tricks to get you started, we have released two packages: WebTwig and WebJS. These are useful for building lightweight frontends with JavaScript components such as sliders, image galleries, and more — for situations where depending on React would be overkill. We’re going to follow up this guide with a blog post going into more detail on these soon.

We encourage you to join the Sulu community on Slack, and take a look at our Services & Support if you want to get up-and-running faster, for example if you have a project with a tight timeline.

Last Updated 22. October 2020

You might also be interested in these articles

Blocks

Structured Content with Blocks

In this guide we explain what Blocks are for and…
Learn more
Bring Your Own Entity

Leverage Sulu's admin UI for Symfony applications

Sulu’s intuitive admin interface brings together…
Learn more