Drupal Planet

PreviousNext: Bare Templates: Removing Unnecessary Markup in Twig files

2 dni 9 godzin ago

In most of the projects we build, the HTML markup provided by core just gets in the way. There is way too many wrapper divs. This can cause issues when trying to create lean markup that matches what is produced in a generated styleguide.

In this post, I'll introduce you to the concept of bare templates, and how you can remove unnecessary markup from your Twig templates.

by Pasan Gamage / 15 March 2018

In Drupal 8, a couple of themes are shipped by default to serve a common set of end user needs.

Among them are:

  • Bartik: A flexible, recolourable theme with many regions and a responsive, mobile-first layout.
  • Seven: The default administration theme for Drupal 8 was designed with clean lines, simple blocks, and sans-serif font to emphasise the tools and tasks at hand.
  • Stark: An intentionally plain theme with almost no styling to demonstrate default Drupal’s HTML and CSS.
  • Stable: A base theme. Stable theme aggregates all of the CSS from Drupal core into a single theme. Theme markup and CSS will not change so any sub-theme of Stable will know that updates will not cause it to break.
  • Classy: A sub-theme of Stable. Theme designed with lot of markups for beginner themers.

But in an actual business scenario the requirements and expectations of a client towards the look and feel of the website is far more distinct than the themes that are provided in Drupal core.

When building your site based upon one of these themes it is common to face issues with templating during the frontend implementation phase. Quite often the default suggested templates for blocks, nodes, fields etc. contain HTML wrapper divs that your style guide doesn’t require.

Usually the most effective way is to build themes using the Stable theme. In Stable, the theme markup and CSS are fixed between any new Drupal core releases making any sub-theme to less likely to break on a Drupal core update. It also uses the verbose field template support for debugging.

Which leads us to use bare templates.

What is a bare template?

A bare template is a twig file that has the minimum number of HTML wrappers around actual content. It could be simple as a file with a single content output like {{content.name}}

Compared to th traditional approach, bare templates provide benefits such as:

  • Ease of maintenance: With minimum markup the complexity of the template is much lesser making it easy to maintain.
  • Cleaner Markup: The markup will only have the essential or relevant elements where as in traditional approach there are a lot of wrappers leading to a complex output.
  • Smaller page size: Less markup means less page size.
  • Avoids the need for markup removal modules: With bare markup method we do not need to use modules like fences or display suite. Which means less modules to maintain and less configuration to worry about.
Our Example

We need to create a bare template for type field and suggest it to render only field name and field_image of my_vocabulary taxonomy entity. This will avoid Drupal from suggesting this bare template for other fields belonging to different entities.

Field template

Let's have a look at field template which resides at app/core/themes/stable/templates/field/field.html.twig

{% if label_hidden %} {% if multiple %} {% for item in items %} {{ item.content }} {% endfor %} {% else %} {% for item in items %} {{ item.content }} {% endfor %} {% endif %} {% else %} {{ label }} {% if multiple %} {% endif %} {% for item in items %} {{ item.content }} {% endfor %} {% if multiple %} {% endif %} {% endif %}

As you see there is quite a lot of div wrappers used in the default template which makes it difficult to style components. If you are looking for simple output, this code is overkill. There is however, a lot of valuable information is provided in the comments of field.html.twig which we can use.

{# /** * @file * Theme override for a field. * * To override output, copy the "field.html.twig" from the templates directory * to your theme's directory and customize it, just like customizing other * Drupal templates such as page.html.twig or node.html.twig. * * Instead of overriding the theming for all fields, you can also just override * theming for a subset of fields using * @link themeable Theme hook suggestions. @endlink For example, * here are some theme hook suggestions that can be used for a field_foo field * on an article node type: * - field--node--field-foo--article.html.twig * - field--node--field-foo.html.twig * - field--node--article.html.twig * - field--field-foo.html.twig * - field--text-with-summary.html.twig * - field.html.twig * * Available variables: * - attributes: HTML attributes for the containing element. * - label_hidden: Whether to show the field label or not. * - title_attributes: HTML attributes for the title. * - label: The label for the field. * - multiple: TRUE if a field can contain multiple items. * - items: List of all the field items. Each item contains: * - attributes: List of HTML attributes for each item. * - content: The field item's content. * - entity_type: The entity type to which the field belongs. * - field_name: The name of the field. * - field_type: The type of the field. * - label_display: The display settings for the label. * * @see template_preprocess_field() */ #} The code Building the hook.

We will be using hook_theme_suggestions_HOOK_alter() to suggest the two fields to use our bare template when rendering.

It is important to note that only these two fields will be using the bare template and the other fields (if any) in that entity will use the default field.html.twig template to render.

my_custom_theme_theme_suggestions_field_alter (&$hooks, $vars){     // Get the element names passed on when a page is rendered.     $name = $vars['element']['#field_name'];     // Build the string layout for the fields.     // :::     $bare_hooks = [         'taxonomy_term:my_vocabulary:teaser:name',         'taxonomy_term:my_vocabulary:teaser:field_logo',     ];     // Build the actual var structure from second parameter     $hook = implode(':', [         $vars['element']['#entity_type'],         $vars['element']['#bundle'],         $vars['element']['#view_mode'],         $vars['element']['#field_name'],     ]);     // Check if the strings match and assign the bare template.     if (in_array($hook, $bare_hooks, TRUE)) {         $hooks[] = 'field__no_markup';     } }

The hook key field__no_markup mentioned in the code corresponds to a twig file which must reside under app/themes/custom/my_theme/templates/field/field--no-markup.html.twig

Debugging Output

In order to see how this is working, we can fire up PHPStorm and walk the code in the debugger.

As you can see in the output below, the implode() creates the actual var structure from the second parameter. We will use this to compare with the $bare_hooks array we created  fields specific to content entity types that we need to assign the bare template.

Note: As best practise make sure you pass a third argument TRUE to in_array(). Which will validate the data type as well.


Bare Template Markup

The following is the contents of our bare template file. Notice the lack of any HTML?

{# /** * @file * Theme override to remove all field markup. */ #} {% spaceless %} {% for item in items %} {{ item.content }} {% endfor %} {% endspaceless %}

Bare templating can be used for other commonly used templates as well. To make it render a minimal amount of elements.


We can always use custom templating to avoid getting into complicated markups. And have the flexibility to maintain the templates to render for specific entities.

Resources Tagged Style Guides, Twig

Amazee Labs: Launching Kinderregion

2 dni 9 godzin ago
Launching Kinderregion

We’re super excited! The new Kinderregion website has finally launched and brings their motto of Great parents need great tips for trips to life. 

It showcases a wide variety of exciting activities for kids. Families living in Switzerland can now plan a fun day for the whole family by browsing the site. Built on the same framework as Zurich Tourism, Kinderregion showcases highly engaging content that is structured, helpful and of interest to the user. 

Nicole Blum Thu, 03/15/2018 - 09:04 The idea

By building Kinderregion on the same framework as Zurich Tourismus, the new site would have to to offer highly valuable content in a structured and appealing manner. The events section should benefit from the main site’s interactive features such as instant filters and an interactive map based on React. As Kinderregion is a content heavy website, we would need to allow content editors to easily change the front page and the menu. Similarly, we would need the ability to deploy code and configuration changes without losing the customisations done by the client. Just as with zuerich.com, our idea to solve this was using the Panels ecosystem.

The most challenging part of the project

Creating something complex on a tight budget can be tricky. We were, however, able to solve this by re-applying certain existing elements throughout the entire site. Along the way, our team learned a bunch of new things and strengthened their skill sets even more. One highlight being how to override existing styling when working with the sub-template.

The Result

We implemented Kinderregion as a subsite of the main Zurich Tourism website, based on the Domain module. This allows us to share mission content across both websites and most importantly, benefit from the infrastructure that the Zurich Tourism Website already provides. We also added to the permission system and the reactive events filter section on the Landing pages.

The same layout used for zuerich.com is applied to Kinderregion, and is based on the "Panels suite". It is built using "Panels everywhere", which enables us to export the site layout and it’s domain-specific variants to features. Following the same logic, the home page is based on a panel page with different variants for each domain. The mega menu is composed of mini panels, loading into specific menu items through the use of the menu mini panel module. The consistent use of panels for all of these different areas allows the content editors to easily update the front page and makes it possible for us to deploy code and configuration changes, without losing the customisations done by the client. Hence, the sites heavy content is displayed in a coherent and captivating manner.

We loved collaborating with Zurich Tourism again on this new project and also really enjoyed working alongside the creative agency Rosarot Ideennetz throughout the process. All input and guidance has been super valuable and highly appreciated.   

Agiledrop.com Blog: AGILEDROP: Our blog posts from February

2 dni 16 godzin ago
You have already seen what Drupal blogs were trending in the previous month, and now it is time to look at all our blog post from February.    The first blog post in February was What can Drupal agencies expect in 2018 by our Commercial director Iztok. He looked at the technology trends and how they are changing, how can those changes influence on Drupal agencies and what can we expect in the future. What are the conclusions from Drupal Business Survey, including responses from 200 different Drupal agencies? Iztok did a SWOT analysis based on digital agency reports from 2017 and outlooks… READ MORE

MTech, LLC: Drupal 8 Contrib Upgrade Status

2 dni 21 godzin ago
Drupal 8 Contrib Upgrade Status

One of the things I constantly get asked about in the Drupal 8 migrate space is when will migrate be ready for use. With the API being marked stable in 8.5.0, now is a good time to consider upgrading. Upgrading a D6 or D7 site should be ready, especially if you have mainly core modules in use. However, what about when your site used a contrib module or two or ten?

Lucas Hedding Wed, 03/14/2018 - 14:13

Fuse Interactive: Drupal 8 and iMIS - A SAML Story

3 dni 2 godziny ago
Drupal 8 and iMIS - A SAML Story In the summer of 2017, Fuse started work on a new website for the BC Pharmacy Association (BCPhA). This new website was to be built in Drupal 8 and was part of BCPhA’s overhaul of their digital strategy. Among the various requirements of the build, was an integration with an existing third-party system BCPhA used to manage their members. This system had been in use by BCPhA for a while and their existing website integrated into this system. John Wiebe Wed, 03/14/2018 - 08:19

Jacob Rockowitz: My three mistakes in regards to the Contribute module and Drupal

3 dni 4 godziny ago

Figuring out how to improve the sustainability of Drupal needs to be an ongoing discussion with a gradually evolving approach. It is important that Drupal and every Open Source project has an ongoing discussion about sustainability where everyone can share their views and experiment with new ideas and approaches.

The Contribute module is an experiment that ignited a discussion. It is important to recognize what works and what doesn’t, acknowledge and learn from mistakes, and continue to have this discussion. Sure, there will be varying opinions and results, but the discussion must always be permitted to happen.

My first mistake: The Contribute module is definitely not a technical dependency

The Webform module doesn't depend on the Contribute module to function properly. Honestly, I did not expect that adding this dependency would be so disruptive. This was my first mistake... adding any new dependency is disruptive especially if someone is managing a large multisite installation.

Conceptually, the Contribute module's message is for the broader Drupal community. This message is originating from my work on the Webform module, therefore it should have stayed in the Webform module. In time, I hope this message gradually works its way through the Drupal core issue queue and reaches the entire Drupal community.

My second mistake: Not fully thinking through my approach

How people interact and communicate in online communities is interesting (to say the least). The truth is people say and act in ways that they would never do in person. I am a born and raised New Yorker, which requires a thick skin to defend yourself, yet at the same time you need empathy to get along with so many different groups of people.

My first mistake...Read More