• About Pixeldust

PreviousNext: Bare Templates: Removing Unnecessary Markup in Twig files

Published on November 3, 2020

Annertech: Annertech: Web Agency of the Year

Annertech: Web Agency of the Year My fingers are trembling typing this. I can’t believe it. This morning everyone in Annertech land is thinking “did that really just happen?” It appears it did, we are the web agency of the year! Last night, to top off the other three awards we won – best arts […]

Flickr: Registration Desk – Tuesday – DrupalCon Dublin 2016

comprock posted a photo: The Drupal community is one of the largest open source communities in the world. We’re developers, designers, strategists, coordinators, editors, translators, and more. Each year, we meet at DrupalCamps, meetups, and other events in more than 200 countries. But once a year, our community comes together in a European city for […]

Flickr: Sprint Lounge – Tuesday – DrupalCon Dublin 2016

comprock posted a photo: The Drupal community is one of the largest open source communities in the world. We’re developers, designers, strategists, coordinators, editors, translators, and more. Each year, we meet at DrupalCamps, meetups, and other events in more than 200 countries. But once a year, our community comes together in a European city for […]

Flickr: Tuesday – DrupalCon Dublin 2016

comprock posted a photo: The Drupal community is one of the largest open source communities in the world. We’re developers, designers, strategists, coordinators, editors, translators, and more. Each year, we meet at DrupalCamps, meetups, and other events in more than 200 countries. But once a year, our community comes together in a European city for […]

Flickr: David & Paul – Scout masters – Wednesday – DrupalCon Dublin 2016

comprock posted a photo: The Drupal community is one of the largest open source communities in the world. We’re developers, designers, strategists, coordinators, editors, translators, and more. Each year, we meet at DrupalCamps, meetups, and other events in more than 200 countries. But once a year, our community comes together in a European city for […]

Flickr: Jam interview – Wednesday – DrupalCon Dublin 2016

comprock posted a photo: The Drupal community is one of the largest open source communities in the world. We’re developers, designers, strategists, coordinators, editors, translators, and more. Each year, we meet at DrupalCamps, meetups, and other events in more than 200 countries. But once a year, our community comes together in a European city for […]

Flickr: Sprinters wanted – Wednesday – DrupalCon Dublin 2016

comprock posted a photo: The Drupal community is one of the largest open source communities in the world. We’re developers, designers, strategists, coordinators, editors, translators, and more. Each year, we meet at DrupalCamps, meetups, and other events in more than 200 countries. But once a year, our community comes together in a European city for […]

Flickr: Sprint Lounge – Wednesday – DrupalCon Dublin 2016

comprock posted a photo: The Drupal community is one of the largest open source communities in the world. We’re developers, designers, strategists, coordinators, editors, translators, and more. Each year, we meet at DrupalCamps, meetups, and other events in more than 200 countries. But once a year, our community comes together in a European city for […]

Leopathu: Dynamic Block Weight in Drupal 8

In such a time, i want to place blocks in sidebar region with the dynamic weight. It means the blocks should render in different position for each page request. I have searched and tried lots of method but unfortunately i can’t find proper method to do that. So i have decided to do that with […]

Agiledrop.com Blog: AGILEDROP: Drupal‘s path from 4.0 to 8.0

Last time we guided you through early beginnings of Drupal. We explained how all started and how first versions of Drupal were made. This time we will look how this open-source content-management framework evolved from its fourth to its latest, eight version. Drupal 4.0 Drupal’s fourth version was released on 15. 6. 2002. It became […]

Flickr: Wednesday – DrupalCon Dublin 2016

comprock posted a photo: The Drupal community is one of the largest open source communities in the world. We’re developers, designers, strategists, coordinators, editors, translators, and more. Each year, we meet at DrupalCamps, meetups, and other events in more than 200 countries. But once a year, our community comes together in a European city for […]

OStatic: Web Publishing and Development: Free Tools Abound

Are you involved in DevOps and web development, or are you aiming to be? If so, you’re probably very aware of many of the tools from the open standards and open source arenas that can make your work easier. Still, these are always spreading out at a fast clip and there are some applications and […]

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 Support Service 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 Support Service 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 Support Service’s HTML and CSS.
Stable: A base theme. Stable theme aggregates all of the CSS from Drupal Support Service 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 Support Service 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 Support Service core releases making any sub-theme to less likely to break on a Drupal Support Service 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 Support Service 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 Support Service 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.
Conclusion
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
sqndr.github.io/d8-theming-guide/core-themes/index.html
api.drupal.org/api/drupal/core%21lib%21Drupal Support Service%21Core%21Render%21theme.api.php/function/hook_theme_suggestions_HOOK_alter/8.2.x
drupal-bootstrap.org/api/bootstrap/templates%21block%21block–bare.html.twig/8
www.drupal.org/docs/8/core/themes
www.drupal.org/project/fences
www.drupal.org/project/ds

Tagged

Style Guides, Twig


Source: New feed

REQUEST FOR PROPOSAL

Need a quick project proposal?

Submit the RFP form below and we will send you a project proposal in 48 hours. If you like what you see, we can schedule a call to discuss the project in greater detail.

Step 1 of 2

  • Contact Information

Drupal Support Plans Compared

* Subject to reasonable use. Small fixes and updates must be requested one at a time and take no more than 30 minutes. Only mission-critical tasks are addressed on weekends.

Shopping Cart
There are no products in the cart!
Continue Shopping
0
X