Skip to main content

Blog Post

Accommodating Drupal In Your Components

Last fall at BADCamp it was exciting to see that a component-driven approach to building Drupal 8 themes is becoming the standard. Many people are doing great things to advance this approach, including reducing duplication and simplifying data structures. In the day-long front end summit, and in many sessions and BOFs during BADCamp, great tips were shared for making the most of helper modules, such as the UI Patterns module, as well as techniques that make the most of Pattern Lab, KSS, and other front end systems.

While Drupalers are rejoicing at these exciting advances allowing newfound front end freedoms, there are still a few hoops to be aware of in order to make the most of Drupal, especially for a newcomer who might be eager to shove aside a lot of what Drupal provides. Some of these things, like contextual links, are nice-to-haves that can make life easier for content administrators. However, other things that are easily dismissed in a component-driven approach, like letting Drupal fully render fields, can cause headaches further on if they’re ignored, and make life difficult when it comes to keeping your front end forward-compatible with Drupal.
 

A Quick Recap of the Component-Driven Approach

At its basic level, the component-driven approach to Drupal theming means:

  1. Breaking your site’s interface down into independent components.
  2. Organizing those components into a system of reusable parts (i.e., the Atomic Design philosophy).
  3. Build out those parts however you see fit in a standalone presentation platform that supports twig (i.e., a KSS, or Pattern Lab style guide), with the pieces of those components that can change set up as variables in the twig files.

These component twig files that you use to build your system of reusable parts essentially serve as replacements for the templates in your Drupal theme (field.html.twig, block.html.twig, node.html.twig, etc.) You’ll still need the Drupal templates -- for now, see the UI Patterns module note at the end -- but they only serve as the “presenter” that helps map values from Drupal to the appropriate variables in your component template. The biggest payoffs with this approach are:

  1. Build things how you like them! You’re in control of the markup, and don’t necessarily have to be a seasoned Drupal developer to dive in.
  2. Back end setup, and front end build out can happen at the same time.
  3. A more organized, and structured presentation layer that’s not strictly tied to Drupal, and could potentially be repurposed for other platforms.

For a deeper dive into the components-driven approach, be sure to check out Mario Hernandez’s blog post series on integrating components into Drupal: Part 1, Part 2, and Part 3.

So if you’re not following a component-driven approach already, I’m sure you can see why it’s becoming popular. However, before diving in, here are a few things to consider to help you keep your approach forward-compatible with Drupal, and hopefully avoid headaches.
 

When It Comes To Fields, Let Drupal Do Its Thing

As we know, the default field markup in Drupal 8 is abstracted to account for field labels, and multiple values. This means that by default in Drupal even a simple, single value text field is going to render with multiple layers of <div>s wrapping the value of the field. However, let’s say you have a callout component in your style guide that includes an optional subtitle field. You’d probably mark that up with just a single, semantic element, like this:
 

{% if subtitle %}
 <h3 class=”callout__subtitle”>{{ subtitle }}</h3>
{% endif %}


And let’s say on the Drupal side of things you’re going use a custom block type for adding callout components to your site. Therefore, in the block--callout.html.twig template that serves as the “presenter” for mapping Drupal values to the component template, you’d have something like this:
 

{% include ‘@custom_theme/callout/callout.twig’ with {
  ...
  ‘subtitle’: content.field_subtitle
  ...
} %}


Since we’re letting Drupal render the subtitle field in our block template, we’d end up with all the default field markup inside our <h3>, which isn’t what we want at all.

While the quickest solution may be to pull out the value of the subtitle field from the render array for the field, and pass that to the component template...
 

‘subtitle’: content.field_subtitle.0['#context].value 


...this can come back to bite you later because of the way Drupal 8 handles caching. One option that’s more cache-friendly is to use the Twig Field Value module. This module gives you custom filters that help you safely pluck the value you need from the render array for the field:
 

‘subtitle’: content.field_subtitle|field_value


This is better, but we’re still shoving aside how Drupal adds attributes to the field markup. We’d only have our custom class on the <h3> for the subtitle, with no way for modules in the Drupal ecosystem to inject their classes or other attributes. As some of the “Outside-In” initiatives in Drupal start to mature this will become increasingly important if you want to take advantage of them. What follows are some options for how you can make your components more “loyally” accommodate Drupal.
 

Follow Drupal’s Lead For Field Markup

First, you could markup your component templates with additional wrappers that include only your classes, which would apply styling to the semantic element included in the variable output of your component template. Understandably, this could lead to a bit more bloated styling and markup, plus require you to include markup in the sample data that your style guide uses. Example:

Component markup:

{% if subtitle %}
  <div class=”callout__subtitle-wrapper”>
    {{ subtitle }}
  </div>
{% endif %}

 

Component placeholder data in the style guide:

{
  “subtitle”: “<h3 class=\”callout__subtitle\”>Subtitle Text</h3>”
}

 

In this case, when the component is implemented on the Drupal side of things, you would create a custom field template for the subtitle field, where you would change the markup to use only a single <h3>, plus add the “callout__subtitle” class via the Drupal addClass() function.

Drupal field template for the subtitle field in our “callout” custom block type:
 

<h3{{ attributes.addClass(‘callout__subtitle’) }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</h3>

 

 

But Wait, I Want Control Of My Markup!

The previous option somewhat defeats the purpose of the markup freedom you get with a component driven approach, so you may want to instead consider leaving the component markup nice and lean, and just use a <span> tag for the subtitle field where the Drupal-specific attributes can be applied.

Component markup:

{% if subtitle %}
  <h3 class=”callout__subtitle”>
    {{ subtitle }}
  </h3>
{% endif %}

 

Component placeholder data in the style guide:

{
  “subtitle”: “Subtitle Text”
}

 

Drupal field template for the subtitle field in our “callout” custom block type:

<span{{ attributes }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</span>

 

This works pretty nicely, but you may find that those Drupal attributes really need to be output where they were intended: the main wrapper for the field.
 

Twig Embed To The Rescue

A good middle ground for keeping your markup lean, but still loyally accommodating Drupal attributes, is to use twig embed blocks in your component template. This means you could put whatever you want inside the embed block declaration for the subtitle field in the component template, and on the Drupal side when the callout component is integrated via a twig embed, we simply swap that subtitle block with something else. Example:

Component markup:

{% block callout_subtitle %}
{% if subtitle %}
  <h3 class=”callout__subtitle”>
    {{ subtitle }}
  </h3>
{% endif %}
{% endblock %}

 

Component placeholder data in the style guide:

{
  “subtitle”: “Subtitle Text”
}

 

Drupal block template for integrating a callout component:

{% embed ‘@custom_theme/callout/callout.twig’ with {
  ...
  ‘subtitle’: content.field_subtitle
  ...
} %}
  {% block callout_subtitle %}
    {{ subtitle }}
  {% endblock %}
{% endembed %}

 

 

Drupal field template for the subtitle field in our “callout” custom block type:

<h3{{ attributes.addClass(‘callout__subtitle’) }}>
  {%- for item in items -%}
    {{ item.content }}
  {%- endfor -%}
</h3>

 

 

Accommodate Attributes All The Way Up

Now that we’ve established some options for accommodating Drupal at the field level, let’s take a look at how to accommodate Drupal in the block template for our callout component example.

One key Drupal feature that’s extremely helpful for content administrators is contextual links. To make these work in our callout component example we’ll need to accommodate the Drupal attributes variable on the main wrapper of the component template, plus include the title_prefix/title_suffix variables. These are what Drupal needs to inject the contextual links into a template.

Since the attributes variable can include class, id, and data attributes in one variable, we need to make sure we only combine Drupal’s classes with ours, and let the other attributes render without Drupal classes. This can be accomplished on the main wrapper of our callout component template:

<div class=”callout {{ attributes ? attributes.class }}”{{ attributes ? attributes|without(‘class’) }}>

 

Note that the ‘without’ twig filter in this example is a Drupal-specific filter, so for your style guide you’ll want to make sure you’re using one that supports Drupal’s custom filters (both KSS node, and Pattern Lab have configuration options that support Drupal twig filters.)

The other thing you’ll want to include to make sure contextual links get injected are the title_prefix/title_suffix variables. You typically will want to include this around the markup for the main title of the component:

{{ title_prefix }}
<h3 class=”callout__title”>
  {{ title }}
</h3>
{{ title_suffix }}

 

 

Make Sure Empty Means Empty

You may recall when first discussing the subtitle for our callout component it was mentioned that it would be an optional field, and in our component template we include an ‘if’ statement to check for a populated subtitle before outputting its related markup. One thing to keep in mind when letting Drupal fully render fields is that even though no content may have been entered for the subtitle on the Drupal side, your component may still read the value of the rendered field as not being empty, and proceed with outputting the markup inside the if statement. This is especially problematic when you have twig debug turned on in your theme.

A reliable way to avoid false positives when checking for empty fields is to check the results of a field after applying the render and trim filters. Example:

‘subtitle’ = content.field_subtitle|render|trim is not empty ? content.field_subtitle


Leave No Content Unrendered

Finally, one last step we’ll want to take in our “presenter” template, is to make sure we allow Drupal to go ahead and do its render thing on the main content variable of the block, even though we’re only interested passing specific field values to our component template. This is again is to help avoid headaches with how caching is handled (read more about this here: https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays). We also need to make sure that we exclude the fields we passed over to our component template since we don’t want them to actually be output in the Drupal template. Example:

{{ content|without(‘field_title’, ‘field_subtitle’, ‘body’) }}


What The Future Holds

As mentioned in the beginning there is also UI Patterns module that many are embracing for a component-driven approach to Drupal site building. The benefit of this module is that it eliminates the need for the “presenter” template when integrating your components.

For now, though, if you find yourself in a position where your Drupal templates are having to serve as the presenter for your components, make sure to consider these ways of keeping things as forward-compatible as possible with Drupal, so that you can take advantage of new Drupal initiatives as their rolled out, and save yourself some headaches later on.

Additional Resources
5 Advantages of Component Driven Theming | Video
Building Components: Breaking it Down | Blog
5 Aspects of Component Driven Back End Development with Drupal 7 | VIdeo

Eric Huffman

Meet team member, Eric Huffman

Eric has over seven years of experience working with Drupal as a developer, themer, and site builder starting with Drupal 6 in 2008. His passion lies in designing and building...

Learn more about Eric >