Wrights HQ

A blog by Ian Wright - Front-end web developer

I have built multiple sites within Drupal 8 now, some brochure & a few more complex sites but in all cases of Drupal 8 the front-end theming is achieved with twig.

What is twig?

Twig is a modern template engine for PHP 

  • Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.
  • Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.
  • Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.

Separating the front-end and back-end (Decoupled architecture).

Drupal 8 takes advantage of having a decoupled system, meaning that front-end developers now have full control of the sites rendered markup allowing them to give the user a better experience and cleaner markup. As a front-end developer it also means I do not need to know the full in and outs of the systems architecture to create templates though I do have a good understanding still – you can see this from my dev diary.

Helpful twig markup

The below markup is for use within a page template, page.html.twig.

Render a region

{{ page.content }}

Render the current years date (useful for copyright)

© {{ 'now'|date('Y') }}

The below markup is for use within a node template, node.html.twig.

Render the node title

{{ label }}

Render a specific field

{{ content.field_name }}

Render content without a field

{{ content|without('field_name_one', 'field_name_two') }}

Formatting dates

{{ node.createdTime|date(format='d F Y') }}

Create a relative path

{{ path('entity.node.canonical', {'node': node.id }) }}

Create an absolute path

{{ url('entity.node.canonical', {'node': node.id}) }}

Shared markup

If you ever find you need to have the same piece of content across multiple node templates you can create a twig file & then included it within a template.

Create a new file, e.g.


Within your node template you can now include this with.

{% include '@themename/includes/shared-content.html.twig' %}

Add attributes to field items e.g. field.html.twig (Anywhere where you print {{ item.content }})

{{ item.content|merge({'#options' : {'attributes': {'class': ['class--one', 'class--two']}}}) }}

The below markup is global & useful for any template.

Add classes (inline)

{{ attributes.addClass('class--one', 'class--two') }}

Add classes (dynamically)

  set classes = [
    node.isPromoted() ? 'is-promoted',
    node.isSticky() ? 'is-sticky',
    not node.isPublished() ? 'is-unpublished',
    view_mode ? view_mode|clean_class,

{{ attributes.addClass(dynamic_classes) }}