Feb 15 2018
Feb 15

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

Nov 13 2017
Nov 13
November 13th, 2017

Welcome to the fourth episode in our video series for Emulsify 2.x. Emulsify 2.x is a new release that embodies our commitment to component-driven design within Drupal. We’ve added Composer and Drush support, as well as open-source Twig functions and many other changes to increase ease-of-use.

In this video, we’re going to teach you how to best use a DRY Twig approach when working in Emulsify. This blog post accompanies a tutorial video, embedded at the end of this post.

DRYing Out Your Twigs

Although we’ve been using a DRY Twig approach in Emulsify since before the 2.x release, it’s a topic worth addressing because it is unique to Emulsify and provides great benefit to you workflow. After all, what drew you to component-driven development in the first place? Making things DRY of course!

In component-driven development, we build components once and reuse them together in different combination—like playing with Lego. In Emulsify, we use Sass mixins and BEM-style CSS to make our CSS as reusable and isolated as possible. DRY Twig simply extends these same benefits to the HTML itself. Let’s look at an example:

Non-DRY Twig:

<h2 class=”title”> <a class=”title__link” href=”/”>Link Text</a> </h2> <h2class=title><aclass=title__link” href=/>LinkText</a>

DRY Twig:

<h2 class=”title”> {% include "@atoms/01-links/link/link.twig" with { "link_content": “Link Text”, "link_url": “/”, "link_class": “title__link”, } %} </h2> <h2class=title>{%include"@atoms/01-links/link/link.twig"with{"link_content":LinkText,"link_url":/,"link_class":title__link”,

The code with DRY Twig is more verbose, but by switching to this method, we’ve now removed a point of failure in our HTML. We’re not repeating the same HTML everywhere! We write that HTML once and reuse it everywhere it is needed.

The concept is simple, and it is found everywhere in the components directory that ships in Emulsify. HTML gets written mostly as atoms and is simply reused in larger components using the default include, extends or embed functions built into Twig. We challenge you to try this in a project, and see what you think.

[embedded content]

Thanks for following our Emulsify 2.x tutorials. Miss a post? Read the full series here.

Pt 1: Installing Emulsify | Pt 2: Creating your Emulsify 2.0 Starter Kit with Drush | Pt 3: BEM Twig Function | Pt 4: DRY Twig Approach | Pt 5: Building a Full Site Header in Drupal

Just need the videos? Watch them all on our channel.

Download Emulsify

Web Chef Evan Willhite
Evan Willhite

Evan Willhite is a frontend engineer at Four Kitchens who thrives on creating delightful digital experiences for users, clients, and fellow engineers. He enjoys running, hot chicken, playing music, and being a homebody with his family.

Oct 26 2017
Oct 26
October 26th, 2017

Welcome to the third episode in our video series for Emulsify 2.x. Emulsify 2.x is a new release that embodies our commitment to component-driven design within Drupal. We’ve added Composer and Drush support, as well as open-source Twig functions and many other changes to increase ease-of-use.

In this video, we’re going to teach you how Emulsify works with the BEM Twig extension. This blog post accompanies a tutorial video, embedded at the end of this post.

Background

In Emulsify 2.x, we have enhanced our support for BEM in Drupal by creating the BEM Twig extension. The BEM Twig extension makes it easy to deliver classes to both Pattern Lab and Drupal while using Drupal’s Attributes object. It also has the benefit of simplifying our syntax greatly. See the code below.

Emulsify 1.x:

{% set paragraph_base_class_var = paragraph_base_class|default('paragraph') %} {% set paragraph_modifiers = ['large', 'red'] %} <p class="{{ paragraph_base_class_var }}{% for modifier in paragraph_modifiers %} {{ paragraph_base_class_var }}--{{ modifier }}{% endfor %}{% if paragraph_blockname %} {{ paragraph_blockname }}__{{ paragraph_base_class_var }}{% endif %}"> {% block paragraph_content %} {{ paragraph_content }} {% endblock %} </p> {%setparagraph_base_class_var=paragraph_base_class|default('paragraph')%}{%setparagraph_modifiers=['large','red']%}<pclass="{{ paragraph_base_class_var }}{% for modifier in paragraph_modifiers %} {{ paragraph_base_class_var }}--{{ modifier }}{% endfor %}{% if paragraph_blockname %} {{ paragraph_blockname }}__{{ paragraph_base_class_var }}{% endif %}">  {%blockparagraph_content%}    {{paragraph_content }}  {%endblock%}

Emulsify 2.x:

<p {{ bem('paragraph', ['large', 'red']) }}> {% block paragraph_content %} {{ paragraph_content }} {% endblock %} </p> <p{{bem('paragraph',['large','red'])}}>  {%blockparagraph_content%}    {{paragraph_content }}  {%endblock%}

In both Pattern Lab and Drupal, this function above will create p class=”paragraph paragraph--large paragraph--red”, but in Drupal it will use the equivalent of p{{ attributes.addClass('paragraph paragraph--large paragraph--red') }}, appending these classes to whatever classes core or other plugins provide as well. Simpler syntax + Drupal Attributes support!

We have released the BEM Twig function open source under the Drupal Pattern Lab initiative. It is in Emulsify 2.x by default, but we wanted other projects to be able to benefit from it as well.

Usage

The BEM Twig function accepts four arguments, only one of which is required.

Simple block name:
h1 {{ bem('title') }}

In Drupal and Pattern Lab, this will print:

h1 class="title"

Block with modifiers (optional array allowing multiple modifiers):

h1 {{ bem('title', ['small', 'red']) }}

This creates:

h1 class="title title--small title--red"

Element with modifiers and block name (optional):

h1 {{ bem('title', ['small', 'red'], 'card') }}

This creates:

h1 class="card__title card__title--small card__title--red"

Element with block name, but no modifiers (optional):

h1 {{ bem('title', '', 'card') }}

This creates:

h1 class="card__title"

Element with modifiers, block name and extra classes (optional, in case you need non-BEM classes):

h1 {{ bem('title', ['small', 'red'], 'card', ['js-click', 'something-else']) }}

This creates:

h1 class="card__title card__title--small card__title--red js-click something-else"

Element with extra classes only (optional):

h1 {{ bem('title', '', '', ['js-click']) }}

This creates:

h1 class="title js-click"

Ba da BEM, Ba da boom

With the new BEM Twig extension that we’ve added to Emulsify 2.x, you can easily deliver classes to Pattern Lab and Drupal, while keeping a nice, simple syntax. Thanks for following along! Make sure you check out the other posts in this series and their video tutorials as well!

[embedded content]

Thanks for following our Emulsify 2.x tutorials. Miss a post? Read the full series is here.

Pt 1: Installing Emulsify | Pt 2: Creating your Emulsify 2.0 Starter Kit with Drush | Pt 3: BEM Twig Function | Pt 4: DRY Twig Approach| Pt 5: Building a Full Site Header in Drupal

Just need the videos? Watch them all on our channel.

Download Emulsify

Web Chef Evan Willhite
Evan Willhite

Evan Willhite is a frontend engineer at Four Kitchens who thrives on creating delightful digital experiences for users, clients, and fellow engineers. He enjoys running, hot chicken, playing music, and being a homebody with his family.

May 24 2017
May 24
May 24th, 2017

In the last post, we introduced Emulsify and spoke a little about the history that went into its creation. In this post, we will walk through the basics of Emulsify to get you building lovely, organized components automatically added to Pattern Lab.

Prototyping

Emulsify is at its most basic level a prototyping tool. Assuming you’ve met the requirements and have installed Emulsify, running the tool is as simple as navigating to the directory and running `npm start`. This task takes care of building your Pattern Lab website, compiling Sass to minified CSS, linting and minifying JavaScript.

Also, this single command will start a watch task and open your Pattern Lab instance automatically in a browser. So now when you save a file, it will run the appropriate task and refresh the browser to show your latest changes. In other words, it is an end-to-end prototyping tool meant to allow a developer to start creating components quickly with a solid backbone of automation.

Component-Based Theming

Emulsify, like Pattern Lab, expects the developer to use a component-based building approach. This approach is elegantly simple: write your DRY components, including your Sass and JavaScript, in a single directory. Automation takes care of the Sass compilation to a single CSS file and JavaScript to a single JavaScript file for viewing functionality in Pattern Lab.

Because Emulsify leverages the Twig templating engine, you can build each component HTML(Twig) file and then use the Twig functions include, embed and extends to combine components into full-scale layouts. Sound confusing? No need to worry—there are multiple examples pre-built in Emulsify. Let’s take a look at one below.

Simple Accordion

Below is a simple but common user experience—the accordion. Let’s look at the markup for a single FAQ accordion item component:

<dt class="accordion-item__term">What is Emulsify?</dt>
<dd class="accordion-item__def">A Pattern Lab prototyping tool and Drupal 8 base theme.</dd>

If you look in the components/_patterns/02-molecules/accordion-item directory, you’ll find this Twig file as well as the CSS and JavaScript files that provide the default styling and open/close functionality respectively. (You’ll also see a YAML file, which is used to provide data for the component in Pattern Lab.)

But an accordion typically has multiple items, and HTML definitions should have a dl wrapper, right? Let’s take a look at the emulsify/components/_patterns/03-organisms/accordion/accordion.twig markup:

<dl class="accordion-item">
  {% for listItem in listItems.four %}
    {% include "@molecules/accordion-item/accordion-item.twig"
      with {
        "accordion_item": listItem.headline.short,
        "accordion_def": listItem.excerpt.long
      }
    %}
  {% endfor %}
</dl>

Here you can see that the only HTML added is the dl wrapper. Inside of that, we have a Twig for loop that will loop through our list items and for each one include our single accordion item component above. The rest of the component syntax is Pattern Lab specific (e.g., listItems, headline.short, excerpt.long).

Conclusion

If you are following along in your own local Emulsify installation, you can view this accordion in action inside your Pattern Lab installation. With this example, we’ve introduced not only the basics of component-based theming, but we’ve also seen an example of inheriting templates using the Twig include function. Using this example as well as the other pre-built components in Emulsify, we have what we need to start prototyping!

In the next article, we’ll dive into how to implement Emulsify as a Drupal 8 theme and start building a component-based Drupal 8 project. You can also view a recording of a webinar we made in March. Until then, see you next week!

Recommended Posts

  • Webinar presented by Brian Lewis and Evan Willhite 15-March-2017, 1pm-2pm CDT Modern web applications are not built of pages, but are better thought of as a collection of components, assembled…
  • Welcome to the final post of our frontend miniseries on style guides! In this installment, the Web Chefs talk through how we chose Pattern Lab over KSS Node for Four…
  • Shared Principles There is no question that the frontend space has exploded in the past decade, having gone from the seemingly novice aspect of web development to a first-class specialization.…
Evan Willhite
Evan Willhite

Evan Willhite is a frontend engineer at Four Kitchens who thrives on creating delightful digital experiences for users, clients, and fellow engineers. He enjoys running, hot chicken, playing music, and being a homebody with his family.

Development

Blog posts about backend engineering, frontend code work, programming tricks and tips, systems architecture, apps, APIs, microservices, and the technical side of Four Kitchens.

Read more Development
May 17 2017
May 17
May 17th, 2017

Shared Principles

There is no question that the frontend space has exploded in the past decade, having gone from the seemingly novice aspect of web development to a first-class specialization. At the smaller agency level, being a frontend engineer typically involves a balancing act between a general knowledge of web development and keeping up with frontend best practices. This makes it all the more important for agency frontend teams to take a step back and determine some shared principles. We at Four Kitchens did this through late last summer and into fall, and here’s what we came up with. A system working from shared principles must be:

1. Backend Agnostic

Even within Four Kitchens, we build websites and applications using a variety of backend languages and database structures, and this is only a microcosm of the massive diversity in modern web development. Our frontend team strives to choose and build tools that are portable between backend systems. Not only is this a smart goal internally but it’s also an important deliverable for our clients as well.

2. Modular

It seems to me the frontend community has spent the past few years trying to find ways to incorporate best practices that have a rich history in backend programming languages. We’ve realized we, too, need to be able to build code structures that can scale without brittleness or bloat. For this reason, the Four Kitchens frontend team has rallied around component-based theming and approaches like BEM syntax. Put simply, we want the UI pieces we build to be as portable as the structure itself: flexible, removable, DRY.

3. Easy to Learn

Because we are aiming to build tools that aren’t married to backend systems and are modular, this in turn should make them much more approachable. We want to build tools that help a frontend engineer who works in any language to quickly build logically organized component-based prototypes quickly and with little ramp-up.

4. Open Source

Four Kitchens has been devoted to the culture of open-source software from the beginning, and we as a frontend team want to continue that commitment by leveraging and building tools that do the same.

Introducing Emulsify

Knowing all this, we are proud to introduce Emulsify—a Pattern Lab prototyping tool and Drupal 8 starterkit theme. Wait… Drupal 8 starterkit you say? What happened to backend agnostic? Well, we still build a lot in Drupal, and the overhead of it being a starterkit theme is tiny and unintrusive to the prototyping process. More on this in the next post.
[NB: Check back next week for our next Emulsify post!]

With these shared values, we knew we had enough of a foundation to build a tool that would both hold us accountable to these values and help instill them as we grow and onboard new developers. We also are excited about the flexibility that this opens up in our process by having a prototyping tool that allows any frontend engineer with knowledge in any backend system (or none) to focus on building a great UI for a project.

Next in the series, we’ll go through the basics of Emulsify and explain its out-of-the-box strengths that will get you prototyping in Pattern Lab and/or creating a Drupal 8 theme quickly.

Recommended Posts

Evan Willhite
Evan Willhite

Evan Willhite is a frontend engineer at Four Kitchens who thrives on creating delightful digital experiences for users, clients, and fellow engineers. He enjoys running, hot chicken, playing music, and being a homebody with his family.

Development

Blog posts about backend engineering, frontend code work, programming tricks and tips, systems architecture, apps, APIs, microservices, and the technical side of Four Kitchens.

Read more Development
Jun 15 2016
Jun 15

Whilst working on a Drupal 8 project, we found that cache tags for a Block Content entity embedded in the footer weren't bubbling up to the page cache.

Read on to find out how we debugged this and how you can ensure this doesn't happen to you too.

The problem

On our site we had a Block Content entity embedded in the footer that contained an Entity Reference field which allowed site admins to highlight author profiles. The issue was that if the admin edited this block and changed the referenced authors, or the order of the authors - the changes didn't reflect for anonymous users until the page cache was cleared.

This immediately sounded like an issue with cache tags bubbling.

About cache tags

So what are cache tags. Well lets quote the excellent handbook page:

Cache tags provide a declarative way to track which cache items depend on some data managed by Drupal.

So in our case, as the page is built, all of the content that is rendered has its cache tags bubble up to the page level cache entry. When any of the items that form the page are updated, all cache entries that match that item's tags are flushed. This ensures that if a node or block that forms part of a page is updated, the cache entry for the page is invalidated. For entities, the tags are in the format {entity type}:{entity id} - e.g. node:2 or block_content:7

Clearly this wasn't happening for our block.

Debugging cache tags

So the first step with debugging this issue is to see what cache tags were associated with the page.

Luckily, core lets you do this pretty easily.

In sites/default/services.yml you'll find this line:

http.response.debug_cacheability_headers: false

Simply change it to true, and rebuild your container (clear caches or drush cr). Then browse to your site and view the headers in the Network panel of your developer toolbar. You'll start seeing headers showing you the cache tags like so:

Response headers

Checkout the X-Drupal-Cache-Tags one to see what tags make up the page.

So in our case we could see that the block we were rendering wasn't showing up in the cache tags.

Digging into the EntityViewBuilder for the block and block content entity, we could see that the right tags were being added to the $content variable, but they just weren't bubbling up to the page level.

Rendering individual fields in Twig templates

Now, this particular block had it's own Twig template, we were controlling the markup to ensure that one field was rendered in a grid layout and another was rendered at the end. The block type had two fields, and we were rendering them using something like this:

<div{{ attributes.addClass('flex-grid__2-col') }}>
  {% if label %}
    <h2{{ title_attributes.addClass('section-title--light') }}>{{ label }}</h2>
  {% endif %}
  {% block content %}
    <div class="flex-grid">
      {{ content.field_featured_author }}
    </div>
    <div class="spacing--small-before">
      {{ content.field_more_link }}
    </div>
  {% endblock %}
</div>

i.e We were rendering just field_featured_author and field_more_link from the content variable. And this is the gotcha. You have to render the content variable to ensure that its cache tags bubble up and end up in the page cache.

The fix

There were only two fields on this block content entity, and we wanted control over how they were output. But we also had to render the content variable to make sure the cache tags bubbled. This was a chance for the Twig without filter to rescue the day. The new markup was:

<div{{ attributes.addClass('flex-grid__2-col') }}>
  {% if label %}
    <h2{{ title_attributes.addClass('section-title--light') }}>{{ label }}</h2>
  {% endif %}
  {% block content %}
    {{ content|without('field_featured_author', 'field_more_link') }}
    <div class="flex-grid">
      {{ content.field_featured_author }}
    </div>
    <div class="spacing--small-before">
      {{ content.field_more_link }}
    </div>
  {% endblock %}
</div>

In other words, we still render the fields on their own, but we make sure we also render the top-level content variable, excluding the individual fields using the without filter.

After this change, we started seeing our block content cache tags in the page-level cache tags and as to be expected, changing the block triggered the appropriate flushes of the page cache.

Twig Caching Drupal 8 Cache Tags
May 19 2016
May 19

Introduction

I have had the chance to be involved with 2 fresh builds with Drupal 8 now, I thought I would describe some of the neat things I have found during this time and some of my lessons learned. My hope is that blog post will help you in your journey with Drupal 8.

1. Drupal Console is awesome

Every time you need to generate a custom module, or a new block in a custom module, you can quickly and easily use Drupal Console to produce the code scaffolding for you. This quite easily makes the job of a developer a lot less stressful, and allows you to focus on actually writing code that delivers functionality.

I plucked these example commands that I use frequently from my bash history:

drupal site:mode dev
drupal generate:module
drupal generate:plugin:block
drupal generate:routesubscriber
drupal generate:form:config

Documentation is online but for the most part, the commands are self documenting, if you use the --help option, then you get a great summary on the command, and the other options you can pass in.

The other nice thing is that this is a Symfony Console application, so it should feel very familiar to you if you used another tool written in the same framework.

2. Custom block types are amazing

In Drupal 7 land there was bean which was an attempt to stop making ‘meta’ nodes to fill in content editable parts of complex landing pages. Now, fast forward to Drupal 8, and custom block types are now in Drupal Core.

This basically means as a site builder you now have another really powerful tool at your disposal in order to model content effectively in Drupal 8.

Each custom block type can have it’s own fields, it’s own display settings, and form displays.

Here are the final custom block types on a recent Drupal 8 build:

One downside is that there is no access control per custom block type (just a global permission “administer blocks”), no doubt contrib will step in to fill this hole in the future (does anyone know a module that can help here?). In the mean time there is drupal.org issue on the subject.

I also found it weird that the custom blocks administration section was not directly under the ‘structure’ section of the site, there is another drupal.org issue about normalising this as well. Setting up some default shortcuts really helped me save some time.

3. View modes on all the things

To create custom view modes in Drupal 7 required either a custom module or Dave Reid’s entity_view_mode contrib module. Now this is baked into Drupal 8 core.

View modes on your custom block types takes things to yet another level still as well. This is one more feather in the Drupal site builder’s cap.

4. Twig is the best

In Drupal 7 I always found it weird that you could not unleash a front end developer upon your site and expect to have a pleasant result. In order to be successful the themer would need to know PHP, preprocess hooks, template naming standards, the mystical specific order in which the templates apply and so on. This often meant that a backend and front end developer would need to work together in order to create a good outcome.

With the introduction of Twig, I now feel that theming is back in the hands of the front end developer, and knowledge of PHP is no longer needed in order to override just about any markup that Drupal 8 produces.

Pro tip - use the Drupal Console command drupal site:mode dev to enable Twig development options, and disable Drupal caching. Another positive side effect is that Twig will then render the entire list of templates that you could be using, and which one you actually are using (and where that template is located).

Pro tip: - If you want to use a template per custom block type (to which I did), then you can use this PHP snippet in your theme’s .theme file (taken from drupal.org):

<?php
/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 *
 * @param array $suggestions
 * @param array $variables
 */
function THEMENAME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    array_splice($suggestions, 1, 0, 'block__bundle__' . $variables['elements']['content']['#block_content']->bundle());
  }
}

When looking for a layout manager to help build the more complex landing pages, I came across panelizer + panels IPE. Using panelizer you are able to:

  • create per node layout variants
  • apply a single layout to all nodes of a particular bundle (e.g. all your news articles have the same layout)

The other neat thing is that the layouts themselves are now standardised between all the various layout managers using a contrib module called layout_plugin. Also they are just YAML and Twig. Simple. There is even an effort to get this merged into Drupal 8.2 which I think would be a great idea.

Downside - all JS is still rendered on the page even though the user (e.g. anonymous users) have no access to panelizer. There is a patch on drupal.org to help fix this.

Since starting this build there has also been a stable release of display suite come out for Drupal 8 as well giving you even more options.

6. You can build a rather complex site with very little contributed modules

For this most recent site I build I got away with using only 10 contributed modules (one of which - devel was purely for debugging purposes).

  • ctools
  • google_analytics
  • metatag
  • panels
  • token
  • contact_block
  • devel
  • layout_plugin
  • panelizer
  • pathauto

This means you are inherently building a more stable and supportable site, as most of the functionality now comes out of Drupal core.

In Drupal 7, the contact module was one of those modules to which I never turned on, as it was rather inflexible. You could not change the fields in a UI, nor add email recipients, or have more than 1 form. Now in Drupal 8 you can have as many “contact” forms as you want, each one is fieldable, and can send emails to as many people as needed.

You can also enhance the core module with:

  • contact_block - allows you to place the contact form in a block
  • contact_storage - allows you to store the submissions in the database, rather than firing an email and forgetting about it

There is still a place for webform, namely:

  • large complex form with lots of fields
  • multi-step forms
  • forms you want to ‘save draft’

You can read more about this in the OS training blog post on the contact module.

Downside - I wanted to have a plain page use the path /contact but the contact module registers this path, so pathauto gave my contact page a path of /contact-0. Luckily creating a route subscriber with Drupal Console was painless, so altering the contact module route was very simple to do. I can paste the code here if needed, but most of it is the code that Drupal Console generates for you.

8. PHPunit is bundled into core

Now that Drupal 8 is largely Object Oriented (OO), you are able to test classes using PHPunit. I have wrote about phpunit in the past if you want to know more.

9. Views is in core

This was the main reason why adoption of Drupal 7 was so slow after it’s initial 7.0 release, as everyone needed views to be stable before jumping ship. Now with views bundled into core, views plugins are also being ported at a great rate of knots too.

10. CKEditor is in core

I often found that this was one library that never (or hardly ever) got updated on sites that had been around for a while. More worryingly, CKEditor (the library) would from time to time fix security related issues. Now that this comes with Drupal 8 core, it is just one less thing to worry about.

Also I would love to shout out to Wim Leers (and other contributors) for revamping the image dialog with alignment and caption options. I cannot tell you how much pain and suffering this caused me in Drupal 7.

If you have built a site recently in Drupal 8 and have found anything interesting or exciting, please let me know in the comments. Also keen to see what sites people have built, so post a link to it if it is public.

May 03 2015
May 03

As we’ve said before, enabling organizations to transform digitally is at the heart of Phase2’s focus on content, collaboration, and experience. A key element of effective transformation is the combination of adaptability and foresight – in other words, the ability to see what new technologies are coming, understand their potential, and harness their power for your benefit.

In the world of open source CMS solutions, that imminent technology is Drupal 8. Although a long time coming, Drupal 8 is still an unknown quantity for many organizations. The way we see it, companies’ willingness to pick it up and run with it (strategically!) will play a major role in their success in the coming years.

MSK & Drupal 8, A Commitment to Innovation

Last year, Phase2 teamed up with Memorial Sloan Kettering Cancer Center to act as the organization’s Drupal technology partner after they had made the innovative decision to be Drupal 8 pioneers. The MSK team had more than a simple migration in mind: they endeavored to build one of the very first enterprise-scale Drupal 8 sites, despite the fact that D8 only existed in a beta form at the time. This decision reflected the center’s ability to see the big picture and boldly pursue innovation. In everything from patient care to biomedical research, MSK constantly seeks new ways to advance beyond what was previously thought possible, and their attitude towards digital transformation was no different.

placeit

Major Perks of D8

In addition to the power in core, which allowed the team to use less than ten total modules, there were vast improvements in extensibility, testing, templating, and configuration management.

Extensibility

The ability to extend plugins and services is more available in Drupal 8, with the result that instead of struggling to use yet-to-be-ported contrib modules, our team was free to create custom code specifically fitted to MSK’s needs. The idea of inheritance also made custom code easier to manage.

Object-Oriented Programming

One of the trickiest learning curves of Drupal 8 was also the catalyst for a lot of saved time. Object-oriented programming forced us to take a highly structured approach, isolating our business logic into objects. This results in separated pieces which can move forward despite one another. You can run your migration without knowing how things are going to be themed, and you can theme things without knowing how all content will be structured, etc.

d8 and symfony

Testing

The level of testing integrated directly in Drupal 8 core makes it significantly easier to confidently maintain MSK’s site functionality as Drupal 8 continues to evolve. The existence of self-documenting tests, which weren’t available in Drupal 6, was a great positive change for the MSK team.

External Libraries

Drupal 8’s incorporation of Twig accelerated the theming process. In addition to Twig, the inclusion of external libraries (JavaScript, Backbone, PhpUnit, Guzzle, and Symfony’s YAML, Routing, and Dependency Injection libraries just to name a few) created a great framework for our developers to work in.

Don’t Miss the D8 Train

We fully believe Drupal 8 (even as a beta) is a valuable alternative to Drupal 6 and 7, especially for enterprise organizations that can combine the core with extended custom code. What’s more, the community needs more organizations to take the leap to Drupal 8 to facilitate improvements and provide influential feedback to the community. Phase2 and MSK were able to contribute a significant amount of code back to the project. To move Drupal 8 closer to an official release, more organizations need to invest in its creation through projects of this kind – and Drupal vendors need to be ready to support them.

drupal-relay_1

Drupal 8 is a win-win for enterprises and the Drupal community alike. Are you and your organization ready to transform with Drupal 8? Take the first step by attending our DrupalCon session with Memorial Sloan Kettering (or our session on Drupal 8 for enterprise organizations!). You can learn from the challenges we faced and come away with a list of hints, tricks, and best practices for beginning your own Drupal 8 project. In the meantime, stay tuned to our blog for more on our adventures in Drupal 8.

May 03 2015
May 03

As we’ve said before, enabling organizations to transform digitally is at the heart of Phase2’s focus on content, collaboration, and experience. A key element of effective transformation is the combination of adaptability and foresight – in other words, the ability to see what new technologies are coming, understand their potential, and harness their power for your benefit.

In the world of open source CMS solutions, that imminent technology is Drupal 8. Although a long time coming, Drupal 8 is still an unknown quantity for many organizations. The way we see it, companies’ willingness to pick it up and run with it (strategically!) will play a major role in their success in the coming years.

MSK & Drupal 8, A Commitment to Innovation

Last year, Phase2 teamed up with Memorial Sloan Kettering Cancer Center to act as the organization’s Drupal technology partner after they had made the innovative decision to be Drupal 8 pioneers. The MSK team had more than a simple migration in mind: they endeavored to build one of the very first enterprise-scale Drupal 8 sites, despite the fact that D8 only existed in a beta form at the time. This decision reflected the center’s ability to see the big picture and boldly pursue innovation. In everything from patient care to biomedical research, MSK constantly seeks new ways to advance beyond what was previously thought possible, and their attitude towards digital transformation was no different.

placeit

Major Perks of D8

In addition to the power in core, which allowed the team to use less than ten total modules, there were vast improvements in extensibility, testing, templating, and configuration management.

Extensibility

The ability to extend plugins and services is more available in Drupal 8, with the result that instead of struggling to use yet-to-be-ported contrib modules, our team was free to create custom code specifically fitted to MSK’s needs. The idea of inheritance also made custom code easier to manage.

Object-Oriented Programming

One of the trickiest learning curves of Drupal 8 was also the catalyst for a lot of saved time. Object-oriented programming forced us to take a highly structured approach, isolating our business logic into objects. This results in separated pieces which can move forward despite one another. You can run your migration without knowing how things are going to be themed, and you can theme things without knowing how all content will be structured, etc.

d8 and symfony

Testing

The level of testing integrated directly in Drupal 8 core makes it significantly easier to confidently maintain MSK’s site functionality as Drupal 8 continues to evolve. The existence of self-documenting tests, which weren’t available in Drupal 6, was a great positive change for the MSK team.

External Libraries

Drupal 8’s incorporation of Twig accelerated the theming process. In addition to Twig, the inclusion of external libraries (JavaScript, Backbone, PhpUnit, Guzzle, and Symfony’s YAML, Routing, and Dependency Injection libraries just to name a few) created a great framework for our developers to work in.

Don’t Miss the D8 Train

We fully believe Drupal 8 (even as a beta) is a valuable alternative to Drupal 6 and 7, especially for enterprise organizations that can combine the core with extended custom code. What’s more, the community needs more organizations to take the leap to Drupal 8 to facilitate improvements and provide influential feedback to the community. Phase2 and MSK were able to contribute a significant amount of code back to the project. To move Drupal 8 closer to an official release, more organizations need to invest in its creation through projects of this kind – and Drupal vendors need to be ready to support them.

drupal-relay_1

Drupal 8 is a win-win for enterprises and the Drupal community alike. Are you and your organization ready to transform with Drupal 8? Take the first step by attending our DrupalCon session with Memorial Sloan Kettering (or our session on Drupal 8 for enterprise organizations!). You can learn from the challenges we faced and come away with a list of hints, tricks, and best practices for beginning your own Drupal 8 project. In the meantime, stay tuned to our blog for more on our adventures in Drupal 8.

Jan 14 2015
Jan 14

I'm updating a Drupal 6 theme to Drupal 8.  One thing I'm doing is making the logo in my Twig template a Twig variable instead of hardcoding the path.  Here's how you do it.  This assumes a theme named 'acton', but you'll change that to your own theme's name.

In 'acton.theme', assuming your logo is 'logo.png' in your theme's root:

function acton_preprocess_page(&$variables) {
  $variables['logopath'] = '/' . drupal_get_path('theme','acton') . '/logo.png';
}

In your Twig template, do something like this:

img class="img-responsive" src="{{ logopath }}" />

Done!

Nov 18 2014
Nov 18

As many of us know, Drupal 8 beta was released at the beginning of October which has given us a great preview of the goodies to come. One of those goodies is a new theme engine, Twig, which replaces PHPTemplate. Twig gives us a lot of extra power over our templates and allows us to clean up a lot of the extra cruft that PHPTemplate forced us to add.

So you may be asking, how will our brand new Drupal 8 templates look? Well they are going to be a lot leaner. The extra cruft of php tags, functions, and other miscellaneous bits are no longer needed – in fact, they don’t even work in Twig templates. Arguably, it will be easier to read at a glance what is happening in the Twig versions of Drupal templates. For a great example of how the new templates will look, we can crack open the Views module and compare the templates in the Views module 7.x version to the ones in the Views 8.x version. So let’s compare the views-view.tpl.php file from Views 7.x to views-view.html.twig file in Views 8.x.

Views-compare-part-oneViews-compare-part-two

Twig Comments

Starting from the top, lets work our way down to see what has changed. In the documentation section we can see that for the large block of comments, as well as single line comments, the {# #} syntax is used.

In the list of variables variables that are available to use, you may notice a few other changes. For example, Twig is not raw PHP, so the ‘$’ is not used at the beginning of variable names. Another change is that is that the $classes_array has been replaced by the attributes variable.

Rendering Variables

 Views-compare_example_one

Moving down to line #40 we can see the first instance of a variables rendered using Twig. The double curly bracket syntax, {{ my_variable }}, tells Twig that this is a variable and it needs to be rendered out. A variation of this syntax uses dot-notation to render variables contained in an array/object. This syntax looks like {{ my_variable.property_or_element }}, which makes it extremely easy to use. Dot notation is not used in this particular Twig template.

Twig Filters

Another powerful feature of Twig is template filters. Filters allow us to do simple manipulations of variables. The syntax for using a filter is similar to the syntax for rendering a variable. The difference is that after the variable name, you insert a | (pipe), followed by the name of the filter. For an example to make a string from a variable all lowercase you would do {{ variable_name|lower }} which transform all of the characters to lowercase. If you have used templating systems from other frameworks, such as Angular.js, this syntax may look familiar to you. This particular Views template does not use filters, but you can see examples of different filters on the Twig documentation site. If none of the predefined filters satisfy your requirements, you can extend Twig to create your own filter. The Twig documentation site provides details about creating your own custom filters..

Twig Logic

Views-compare_example_two

Jumping to line #42, we can see the {% %} (curly-bracket and percentage symbol) syntax, which is used for template logic, such as if statements. This syntax tells Twig that we are not rendering something, but rather that we need to process some logic, such as a control structure or loop, in our template.

The Takeaway

This blog post is a high level overview of how Twig templates in Drupal 8 will look.  With Twig, we can choose to use the out-of-the box tools it provides, or we can dive in and extend it with additional features such as new filters. For more information I would highly recommend reading through the Twig documentation for designers and for developers.

Apr 11 2014
Apr 11

I would lie (and would i lie to you ?) if it say that im not extremely excited about theming in Drupal8. One the bigger painpoints in Drupal theming is figuring out where the markup is generated from. In Drupal8 we have build that directly in, i did a little screencast of it & damn its awesome. I will guarantee 7% less cursing from the themers in the future when we move up to Drupal8 : Drupal8 Twig theme debug

If you on Drupal7 & ave a pirates heart & dont want divitis & bloated crappy markup (sorry Drupal) then checkout the mighty mothership, ruler of the 7 seas of Drupal

Apr 07 2014
Apr 07

Dear Themer we the Drupaltwig group need some answers & advice from all of our fellow Drupalistas - We want to make sure that we are creating a theme system that lives up to the wishes of all Drupal8 users - but especially us themers ;)

Recently we changed the theming system from phptemplate to twig. So now is a golden opportunity to fix some of the theming assumptions that have been around for the last 6-10 years in Drupal. The goal in Drupal8 is to make it easier for themers and at the same time keep awesome for the developers and the site builders. We want the best of both worlds!

The Drupaltwig group want to make sure that were on the right track and not making false assumptions about what you want - its completely unofficial, but we will use it as a guideline - and why its called Drupal Theme Surver 2014

Please spread this around to all the themers you know and other good people, Drupal developers, general frontend developer, sitebuilders & maybe even the suits! ...

We want to make sure that we are ending up creating the best possible theme system we can in Drupal8
and we dont end up with a solution that 5-10 elitist Themers want or even worse, a solution nobody actually wants.

So pretty please - with a {{ sugar }} on top : Take the 2014 Themer Survery!

cheers !
Markup Marine mortendk

Apr 01 2014
Apr 01

I finally got to take a long & hard look at fields and why they have so much divitis + a solution of how to change it for Drupal8. It ended up beeing a ton of markup & css examples on a flat html page
take a look please provide feedback, here or on the issue or at my twitter etc.

If its to long to read then heres the short version: Yes we can fix the divitis, but well have to break out of having the same pattern for all kinds of fields (single, multiple, label & without)

the issue on d.o

& the theme system in Drupal8 is gonna be awesome(if you were wondering)

more info about Drupal Twig on drupaltwig.org
the principles we build Drupaltwig on

May 17 2013
May 17
The power of the Twig templating engine

A new theming engine, Twig, is coming along with Drupal 8's adoption of the Symfony framework. And it's downright magical.

Instead of having theme functions that have to be overridden, everything becomes an (easy to read, easy to modify) template. Instead of having to figure out render arrays, themers can use consistent template variables. And instead of having insecure output, Twig sanitizes everything by default.

If you've ever worked on a WordPress or Tumblr theme, the approach will feel pretty similar. Here's what it looks like:

Example of Twig template in Drupal

And oh by the way, it's well-documented — no small point in the Drupal community!

Sound too good to be true? Well, it almost might be, because a lot has to happen in order to get this into Drupal 8. There's a Twig-focused sprint happening right after Drupalcon, so if you think this is great, come pitch in! Because if things don't get done, Twig will be held until Drupal 9. No Drupal themer, veteran or newbie, kitten or human, wants that to happen.

I spoke to Jen Lampton (with a contribution from Fabian Franz) about how Twig will result in happier veteran Drupal themers, happier new Drupal themers, and happier Drupal kittens. Be sure to show up for their featured Drupalcon session (along with Drupal CSS innovator John Albin Wilkins), “Using Twig: The new template engine in Drupal 8,” on Wednesday at 3:45 PM.

IB: What's one thing you're most excited about with Twig?

JL: Replacing the template engine with something completely different means that we get to take a good hard look at absolutely everything in the current theme system, so we can do a clean sweep.

FF: What I love the most about Twig is the syntax, and how it cleverly makes it possible to lazy-render things. The possibilities of having an interpreted language are endless.

IB: Can theme developers start converting/creating their themes now?

JL: No! If you have the time to start converting your own themes, then please, please, please use the time to help us make the theme system what you want it to be — instead. There will be time to convert your themes later, but Drupal itself can only be monumentally improved right now.

IB: Will frontend developers and themers coming from other CMSes — like WordPress — find Twig easier to use?

JL: Yes. Front end developers coming from everywhere will find Twig easier to use. For starters, Twig looks a lot more like HTML, so if you don't know PHP you'll still be right at home. For people who do know PHP and don't know Twig, there will be a learning curve, but it's far far FAR less steep than learning about what Drupal had done to PHPTemplate.

IB: Twig sounds great! What can people do to help make sure it happens for Drupal 8?

JL: There are four main areas where we need help right now, as outlined in our Twig TODO wiki.

1. Help us test all the patches.
2. Help us fix issues with the patches.
3. Help us improve the markup in core (after being converted to Twig).
4. Help us clean up the rest of the theme system.

If people are interested in any one of these four areas, they can come to the sprint immediately following DrupalCon and get some hands-on help making Drupal better. We need all the hands we can get since we are up against some major deadlines, so please please please come help us!

Join Rootwork on Twitter, Facebook and SlideShare.

Learn about Rootwork's services for nonprofits and social change.

May 13 2013
May 13
Drupalcon Portland: May 20-24, 2013

The big news at Drupalcon Portland is that, for the first time at a Drupalcon, we're having separate frontend and user experience (UX) tracks. That means we were able to offer even more sessions targeted directly at frontend developers, and as the local track chair for frontend, I'm really excited about what we've ended up with!

Groundbreaking frontend featured speakers

Jonathan SnookFirst and foremost, of course, we have Jonathan Snook presenting on his concept (and book) Scalable and Modular Architecture for CSS.

MortenDK at Drupalcon SydneySMACSS has had a big impact on a lot of frontend developers and themers — and in fact it's had a huge impact on Drupal itself. The Zen base theme, the most-downloaded Drupal theme out there, has adopted a SMACSS approach.

And Drupal itself is moving toward SMACSS with a re-organization of its CSS in the upcoming Drupal 8 release.

Join Jonathan Snook at Drupalcon Portland on Tuesday, May 21 at 4:30 PM.

Drupal 8 and Twig

Oh yeah, so there's this new version of Drupal coming out pretty soon.

Among the many, many awesome things happening with Drupal 8, one of the most relevant to frontend developers is the adoption (with a little luck) of the Twig templating engine.

Twig, a component of Symfony — a framework being adopted by Drupal 8 — will enable themers to write much cleaner (and safer!) code, and enable module developers to simplify the theming components of their modules.

No joke, at the BADCamp 2012 Twig session, there were literally gasps in the audience as we all saw how cool it was. If you're a themer or a frontend developer, don't miss this!

Join Jen Lampton, Fabian Franz and John Albin Wilkins presenting Twig on Wednesday, May 22 at 3:45 PM.

And so much more!

I've just touched on two of the featured sessions at Drupalcon Portland. In the coming week I'll be posting more about some of the other sessions, but you can browse the frontend sessions right now and start planning to attend your favorites! (Don't forget the User Experience sessions too.)

And if you don't yet have your ticket to Drupalcon Portland, there's still time! Grab your ticket by this Friday and save $50 off the on-site ticket price.

I can't wait to see everyone here in Portland!

Join Rootwork on Twitter, Facebook and SlideShare.

Learn about Rootwork's services for nonprofits and social change.

May 13 2013
May 13

Per Dries's post about Drupal 8 release risk, this post outlines a plan jointly developed by the Drupal core maintainers (Dries, webchick, catch, and alexpott) for getting Twig into core safely. See that post for more background information.

What's up with Twig?

The Twig template engine was originally committed to Drupal 8 live on stage at BADCamp in November 2012, to wild fanfare. Since then, the team has been working on converting all templates and theme functions in Drupal core to use Twig. Thanks to valiant effort by numerous contributors, the PHPTemplate conversions currently stand at ~30% RTBC, and another ~45% at needs review. This is great progress!

Why aren’t the core committers committing?

The short answer is release risk. We are in the “clean up” phase of the Drupal 8 release cycle (http://drupal.org/core/release-cycle#clean-up-phase). Each commit we make should take us one step closer to a Drupal release. In effect, committing an individual Twig patch to core takes us one step further into uncharted territory. At the moment all of our templates are PHPTemplate and hence each conversion commit moves us further away from a release. We obviously can't ship with two theme systems, so unless 100% of templates are converted, we leave Drupal 8 in an unreleasable state.

Solution

We plan to merge all the PHPTemplate to Twig conversions into one patch. Once complete, we will commit this patch into the mainline 8.x branch. The patch will convert all the .tpl.php files to .twig and remove the functionality that allows Drupal 8 to run both theme engines at the same time. This means that Twig commits will not take the 8.x branch further away from a release, and it gives us an exit strategy if they are not complete by code freeze.

The Twig team will:

  • Finish converting all the templates.
  • Provide benchmarking evidence on each issue that the conversion conforms to the acceptance criteria. If other patches are required to be applied in order to meet this requirements then these should added to both the conversion issue and the meta issue.

Core committers will:

  • Review each individual patch and
    • Comment: "+1. Ready for [#1987510]"
    • Status: "closed (duplicate)"
    • Title: prepend '[READY] '
  • Commit the merged patch once all templates have been converted and acceptance criteria have been met.
  • If a Twig patch is isolated to the current Twig code in 8.x then the core committers will commit it immediately. For example: Allow and test for NULL and integer 0 values in Twig templates

Acceptance criteria

The following are necessary in order to perform the final merge of conversions into 8.x:

  • 100% PHPTemplate to Twig conversions are completed
  • 8.x-twig performance is comparable with 8.x PHPTemplate performance, bearing in mind the issues with D8 performance testing - see https://drupal.org/node/1888424#comment-7345926
  • there are no critical Twig follow ups

Once the patch is committed further Twig work should continue on 8.x to:

  • Convert theme functions to Twig
  • Gain the security benefits on Twig
  • Further performance enhancements made possible by moving to Twig
  • Preprocess cleanup
  • Removal of the entire process layer

Important: It is in everyone’s interest that the conversions are finished as soon as possible. In an ideal world, the merge will take place during Drupalcon Portland.

Rollback criteria

If by 17th June the acceptance criteria are not met, then (with regret) an issue will be created to remove Twig from Drupal 8.x. This gives enough to time to create and test the rollback patch before code freeze on 1st July.

Help wanted!

The Twig team has been doing a tremendous job, and we know the front-end community is very excited about this initiative. The time is definitely here to jump in and help the team push this initiaitve past the finish line! Particularly needed are patch reviews (see http://www.youtube.com/watch?v=Bv4PY_ZEP4Q for a helpful screencast on how to do so!), since most issues have patches but can't be RTBCed by people who worked on them.

So grab an issue to review and/or drop by #drupal-twig on IRC if you'd like to help. It's a great way to learn about Drupal 8, meet awesome people, and vastly improve Drupal for front-end developers at once!

May 13 2013
May 13

Per Dries's post about Drupal 8 release risk, this post outlines a plan jointly developed by the Drupal core maintainers (Dries, webchick, catch, and alexpott) for getting Twig into core safely. See that post for more background information.

What's up with Twig?

The Twig template engine was originally committed to Drupal 8 live on stage at BADCamp in November 2012, to wild fanfare. Since then, the team has been working on converting all templates and theme functions in Drupal core to use Twig. Thanks to valiant effort by numerous contributors, the PHPTemplate conversions currently stand at ~30% RTBC, and another ~45% at needs review. This is great progress!

Why aren’t the core committers committing?

The short answer is release risk. We are in the “clean up” phase of the Drupal 8 release cycle (http://drupal.org/core/release-cycle#clean-up-phase). Each commit we make should take us one step closer to a Drupal release. In effect, committing an individual Twig patch to core takes us one step further into uncharted territory. At the moment all of our templates are PHPTemplate and hence each conversion commit moves us further away from a release. We obviously can't ship with two theme systems, so unless 100% of templates are converted, we leave Drupal 8 in an unreleasable state.

Solution

We plan to merge all the PHPTemplate to Twig conversions into one patch. Once complete, we will commit this patch into the mainline 8.x branch. The patch will convert all the .tpl.php files to .twig and remove the functionality that allows Drupal 8 to run both theme engines at the same time. This means that Twig commits will not take the 8.x branch further away from a release, and it gives us an exit strategy if they are not complete by code freeze.

The Twig team will:

  • Finish converting all the templates.
  • Provide benchmarking evidence on each issue that the conversion conforms to the acceptance criteria. If other patches are required to be applied in order to meet this requirements then these should added to both the conversion issue and the meta issue.

Core committers will:

  • Review each individual patch and
    • Comment: "+1. Ready for [#1987510]"
    • Status: "closed (duplicate)"
    • Title: prepend '[READY] '
  • Commit the merged patch once all templates have been converted and acceptance criteria have been met.
  • If a Twig patch is isolated to the current Twig code in 8.x then the core committers will commit it immediately. For example: Allow and test for NULL and integer 0 values in Twig templates

Acceptance criteria

The following are necessary in order to perform the final merge of conversions into 8.x:

  • 100% PHPTemplate to Twig conversions are completed
  • 8.x-twig performance is comparable with 8.x PHPTemplate performance, bearing in mind the issues with D8 performance testing - see https://drupal.org/node/1888424#comment-7345926
  • there are no critical Twig follow ups

Once the patch is committed further Twig work should continue on 8.x to:

  • Convert theme functions to Twig
  • Gain the security benefits on Twig
  • Further performance enhancements made possible by moving to Twig
  • Preprocess cleanup
  • Removal of the entire process layer

Important: It is in everyone’s interest that the conversions are finished as soon as possible. In an ideal world, the merge will take place during Drupalcon Portland.

Rollback criteria

If by 17th June the acceptance criteria are not met, then (with regret) an issue will be created to remove Twig from Drupal 8.x. This gives enough to time to create and test the rollback patch before code freeze on 1st July.

Help wanted!

The Twig team has been doing a tremendous job, and we know the front-end community is very excited about this initiative. The time is definitely here to jump in and help the team push this initiaitve past the finish line! Particularly needed are patch reviews (see http://www.youtube.com/watch?v=Bv4PY_ZEP4Q for a helpful screencast on how to do so!), since most issues have patches but can't be RTBCed by people who worked on them.

So grab an issue to review and/or drop by #drupal-twig on IRC if you'd like to help. It's a great way to learn about Drupal 8, meet awesome people, and vastly improve Drupal for front-end developers at once!

Sep 21 2012
Sep 21

Listen online: 

Join Addi chats while she chats with Jen Lampton about her Drupal history, her current work in Drupal 8, and big, scary animals. Jen is leading up the charge to get a new theme system into Drupal core, based on the Twig template engine, so we talk quite a bit about what that means, how it would change Drupal, and how everyone can help make it happen.

Podcast notes

Release Date: September 21, 2012 - 10:00am

Album:

Length: 31:59 minutes (18.3 MB)

Format: mono 44kHz 80Kbps (cbr)

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web