Wrights HQ
A blog by Ian Wright - Front-end web developer
on Drupal
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.
Twig is a modern template engine for PHP
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.
Render a region
{{ page.content }}
Render the current years date (useful for copyright)
© {{ 'now'|date('Y') }}
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.
/includes/shared-content.html.twig
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']}}}) }}
Add classes (inline)
{{ attributes.addClass('class--one', 'class--two') }}
Add classes (dynamically)
{%
set classes = [
node.bundle|clean_class,
node.isPromoted() ? 'is-promoted',
node.isSticky() ? 'is-sticky',
not node.isPublished() ? 'is-unpublished',
view_mode ? view_mode|clean_class,
'extra--class',
]
%}
{{ attributes.addClass(dynamic_classes) }}