Evolving Web: Drupal Theming Do's and Don'ts

Image removed.

Are you a Drupal enthusiast looking to take your theming game to the next level? Well, you're in for a treat! In this blog post, we're going to dive into some essential best practices for Drupal theming.

View Modes

❌Don’t use the same view mode for everything

✅Do use view modes for unique content displays

View modes are an invaluable tool when it comes to theming in Drupal. They allow you to create unique presentations for your content, tailored to specific use cases. Here's why you should embrace them:

Tailored content display. View modes allow you to customize how your content appears in different contexts. You can make each one look just right, whether it's a teaser on a list page or a full content view.

Field management and formatting. Tired of displaying all the fields, even when you only need a few? View modes let you selectively show or hide specific fields, ensuring a clutter-free design. What’s more, view modes enable you to apply different formatters to each field.

Control referenced entities. View modes are also incredibly useful when displaying referenced entities as you can customize how a referenced entity appears per view mode.

Custom templates. Having different view modes also allows you to create specific templates that you can easily override and customize to your liking.

Some common examples of custom view modes:

  • Search result – used when the content is displayed as part of a search result
  • Featured – used when displaying the content in a more prominent way
  • Embedded – used when embedding the content inside a rich-text editor

Image removed.Here you can see the recipe content type with multiple view modes configured.

Printing Field Values

❌Don’t access entity fields directly

✅Do use the content object when printing field values

 

Accessing and printing out entity fields directly places the burden of displaying fields on you and your code further increasing technical debt. So avoid printing entity fields like this:

{{node.field_example.value}}

Instead, use the content object:

{{content.field_example}}

Using the content object means you'll benefit from field widgets and formatters. There are tons of contrib modules that provide additional field widgets and formatters that you can use. 

The content object also allows you to take advantage of field preprocess functions as well as field templates. These are out-of-the-box theming helpers that allow you to fine-tune the appearance of your fields. This approach is very close to Drupal standards.

However, there's an exception to this rule. You may access entity fields directly when checking raw values (like lists or keys) or when you need to verify the truthiness of a field. In these specific cases, it's acceptable to access the fields directly from the entity object instead of the content object. See the sections on empty fields and ternary operations below for tips on how to check raw values.

Beyond Content Fields

❌Don’t overfocus on fields and forget the rest of your content

✅Do pay attention to internal data and use the without Twig filter

It’s normal to find yourself printing the content fields individually, but it’s essential not to overlook the rest of your content. Here’s what to keep in mind:

Ensure processing of important internal data. Your content may contain essential internal data, such as hidden form tokens or cache tags.

Customize your view mode to hide fields. One of the strengths of view modes is their ability to hide specific fields. By leveraging view modes effectively, you can ensure that certain fields are hidden when they are not needed in a particular context.

Use the without Twig filter. To print the rest of the content effortlessly, you can make use of the without Twig filter. This filter allows you to exclude specific fields from the rendering, ensuring that only the necessary content is displayed.

// Print content fields individually. {{content.field_foo}} {{content.field_bar}} // But don't forget to "flush" the rest of the content. {{content|without('field_foo','field_bar')}}

Clean, Lean Templates

❌Don’t allow clutter and "Drupalisms" to build up

✅Do use contrib modules to tidy up your code 

The Fences and No Markup modules can help you achieve more concise and readable code for cleaner, more efficient templates.

These modules allow you to control the HTML markup and structure of your content without creating unnecessary clutter. Your templates will be easier to maintain and understand as a result.

They also allow for more standardized markup that’s easier to style with CSS. Drupal generates a lot of markup by default, often containing "Drupalisms"—patterns and classes that are specific to the Drupal ecosystem. Fences and No Markup enable you to strip away these Drupal-specific elements.

 

Image removed.Remove wrapper elements with the Fences module or completely remove all default markups with the No Markup module.

Empty Fields

❌Don’t rely on rendering functions to tell you if a field is empty

✅Do check the entity property directly

One area that often goes overlooked is handling empty fields. It’s best practice to check the entity property directly instead of relying on rendering functions to determine if a field is empty. By accessing the raw data, you can efficiently assess whether the field contains content without triggering unnecessary rendering processes.

If you have to render a field before checking if it's empty, do so judiciously. Render the field once and store the result. Then perform your checks on the stored value. This approach minimizes the performance impact associated with repeated rendering calls.

Consider the following example:

{%ifcontent.field_name|renderisnotempty%} {{content.field_name}} {%endif%}

This can be optimized as follows:

{%ifcontent.field_exampleisnotempty%} {%ifnode.field_example.value%} {%ifnotnode.field_example.isEmpty()%}

Or, if rendering is necessary, do it once and test:

{%setrendered_field=content.field_example|render|trim%} {%ifrendered_field%} {{rendered_field}} {%endif%}

Ternary Operations

✅Do use ternary operations to make your code look concise

❌Don’t use them in situations where they might compromise code readability

Simplicity often leads to elegance. One way to achieve a cleaner and more concise codebase is by embracing Twig ternary operations. Here are some practical examples:

Example A: If foo, echo “yes” else echo “no”:

{{foo?'yes':'no'}}

Example B: If foo, echo it, else echo “no”:

{{foo?:'no'}}

or

{{foo?foo:'no'}}

Example C: If foo, echo “yes”, else echo nothing:

{{foo?'yes'}}

or

{{foo?'yes':''}}

Example D: If foo is defined and not null, echo it, “no” otherwise:

{{foo??'no'}}

Example E: If foo is defined (empty values also count), echo it, “no” otherwise:

{{foo|default('no')}}

While Twig ternary operations are excellent for simplifying straightforward conditions, it's essential to use them judiciously. Reserve their use for situations where the conditions are concise and don't compromise code readability.

Twig Features

❌Don’t allow regular PHP code to become bloated and unwieldy

✅Do use Twig to create efficient and maintainable templates

Twig compiles templates down to plain optimized PHP code. Maximizing the potential of Twig goes a long way in creating efficient and maintainable templates. With single directory components (SDCs) becoming part of Drupal core, familiarizing yourself with Twig, and its built-in functions, is now more practical than ever.

Include: Insert Static Template Content

The include statement allows you to insert static template content from another file into your current template. This can be especially handy when you have reusable components or snippets of code that you want to include across multiple templates. 

For example:

{#Includeheadercontentfromaseparatetemplatefile#} {%include'themes/my_theme/templates/header.html.twig'%}

Extends: Template Inheritance

The extends statement is the foundation of template inheritance. It enables you to create a base template with common elements and then extend or override specific sections in child templates. This promotes consistency and reduces redundancy in your theming. Some examples are below.

Base template: base.html.twig

{%blockheader%}{%endblock%} {%blockcontent%}{%endblock%}

Child template: child.html.twig:

{%extends'base.html.twig'%} {%blockheader%} Extendedblock {%endblock%} {%blockcontent%} Thisblockisextended. {%endblock%}

Use: Import Blocks Without Inheriting Structure

The use statement allows you to import blocks from another template without inheriting its entire structure. This can be useful when you want to reuse specific blocks without committing to the entire template. Example:

Block library: block-library.html.twig

{%blockheader%} Product Features Marketplace Company {%endblock%} {%blockfooter%}

Copyright©MyWebsite2023.Allrightsreserved.

{%endblock%} {%blocksidebar%} Thisisasidebar {%endblock%}

Embed: Create Reusable Self-Contained Components

The embed statement is similar to include but with a crucial difference. It allows you to create self-contained components that encapsulate their own logic and styling. This promotes modularity and makes your templates more maintainable. Some examples are below:

Person card: person-card.html.twig

{%blockperson%}

{%blockname%}Name{%endblock%}

{%blockposition%}Position{%endblock%}

{%endblock%} People list: people.html.twig {%embed'person-card.html.twig'%} {%blockname%} BubblesMcFuzzball {%endblock%} {%blockposition%} ChiefBubbleologist {%endblock%} {%endembed%} {%embed'person-card.html.twig'%} {%blockname%} SirReginaldFluffernutter {%endblock%} {%blockposition%} DirectorofSnuggles {%endblock%} {%endembed%}

Section: section.html.twig

{%use'block-library.html.twig'%} {{block('header')}}

Macro: Create Reusable, Parameterized Code Chunks

The macro statement enables you to define reusable, parameterized code chunks. This is particularly useful when you need to repeat a specific operation with variations across your templates.

Button: button.html.twig

{%macrobutton(text,url,color='indigo')%} {{text}} {%endmacro%}

Form actions: form-actions.html.twig

{%import'button.html.twig'asbuttons%} {{buttons.button('PrimaryButton','#','indigo')}} {{buttons.button('SecondaryButton','#','zinc')}}

The Final Word: Simplicity is Key

From the flexibility of view modes to the power of Twig features, each technique that I’ve covered in this article will contribute to cleaner, more maintainable templates. Just remember that simplicity is key—the goal is to strike a balance between conciseness and clarity.

Happy theming!

//--> //--> //-->

+ more awesome articles by Evolving Web

Drupal Association blog: Transitioning from Drupal 7: What's next for your website?

Here's the next part of our ongoing series dedicated to assisting Drupal 7 site owners in upgrading their websites to Drupal 10. There are many great reasons to upgrade. The modern Drupal offers powerful features for content editors including: customizable editorial workflows, a layout builder for your landing pages, a media library that makes managing and reusing media easier than ever, and more. Developers can leverage the most of these advancements.

In our previous blog post, we discussed using our questionnaire to develop a plan, understanding your budget, and deciding whether to work with a certified partner from our list or take the DIY approach for your migration. As we get closer to the start of 2024 and to Drupal 7 End of Life, it's crucial to consider the next phase. Now, you need to secure your website's future but also start to map your information architecture and enhance your content strategy. In this blog post, we'll explore what that means and why these steps are crucial as you prepare to transition away from Drupal 7.

Understanding Information Architecture and Content Strategy

At its core, these steps are vital to ensure a smooth transition to a new version. Mapping information architecture involves creating a blueprint of your website, showcasing where every piece of content is located and how it's interconnected, along with the key content types, views, and taxonomies crucial to your site. This is crucial because when you transition away from Drupal 7 to a new version, having a clear plan ensures that your website's structure remains organized. Such clarity helps prevent issues like data loss, broken links, and confusion for your website visitors.

Drupal offers tools and features empowering site builders and developers to create and manage a structured website tailored to your specific needs.

Additionally, when you assess your content strategy, you're essentially conducting a thorough review of the quality, relevance, and overall effectiveness of the content on your website. This is crucial during migration as it ensures your content remains valuable, fits the new platform's goals, improves user experience, and maintains or boosts SEO rankings. This preparation is vital for a smooth transition and to maintain the integrity of your content in the new setting.

To learn more about information architecture, explore the information architecture guide. For insights into content strategy, refer to this content strategy guide. For a comprehensive checklist when launching a website, visit the major version upgrade documentation.

Here are some recent sessions from DrupalCon worth exploring:

What does End of Life mean for you?

In software terms, End of Life means that the version of that software no longer receives feature updates, bug fixes, or security releases. This last point is the most important. If a security vulnerability is discovered after the end of life date, it may be publicly disclosed, and you will be unable to update your site to protect against the issue. For this reason, we recommend beginning to plan your migration now. 

Whether you want to take advantage of new functionalities with Drupal 10 or opt for another option, we’re here to support you. 

Visit our resource center to migrate from Drupal 7 now, and stay tuned for more blogs in our Drupal 7 End of Life series!

LostCarPark Drupal Blog: Drupal Advent Calendar day 7 - Extra Field

Drupal Advent Calendar day 7 - Extra Field james Thu, 12/07/2023 - 07:00 Image removed.

Welcome back to the Drupal Advent Calendar, and we’re rounding out the first week with the help of Rodrigo Aguilera (rodrigoaguilera), who’s telling us about the Extra Field module.

My choice for the Drupal advent calendar is Extra field because it is a not-so-popular module that helps me in many projects. It falls into a category that I call “Developer little helpers” since it doesn’t provide any immediate interface or functionality but it makes my life a little bit easier.

I like to keep the different representations of entities in display modes and keep the configurability that Drupal offers…

Tags

LN Webworks: Drupal Coding Standards with Git Hooks: All You Need To Know

Image removed.

Think of good code like a well-put-together puzzle—it's strong, looks good, and is easy to tweak. When you're coding with a team or diving into projects like Drupal, sticking to coding standards is a big deal. That's where Git Hooks come in! 

Git Hooks provides a simple and automated way to guarantee that your code consistently adheres to Drupal’s coding standards. By incorporating Drupal Coding Standards with Git Hooks, developers can effortlessly commit and push code that aligns with the community's guidelines. 

Let’s dive deeper into the world of Git Hooks to understand how they work and put them into action for smoother and more standardized coding practices.

The Significance of Drupal Coding Standards

Drupal's coding standards encompass a set of guidelines for writing consistent, well-structured, and maintainable code. These standards cover various aspects of code development, including:

Four Kitchens: Now’s the time to plan your migration to Drupal 10

Image removed.

Laura Johnson

Senior Engineer

Primarily a backend developer, Laura also loves adding new cross-disciplinary skills to her collection, such as working with themes and frontend frameworks.

January 1, 1970

If your organization is still using Drupal 7 or later, migrating to an up-to-date platform for your website has been looming like a weight on your shoulders. The move to Drupal 10 isn’t easy. It requires a migration of your site and a full redesign to take advantage of the new tools the latest version offers.

Not only do you need someone to write that migration, but you also need to secure the budget to undertake a project like this. As you wait for the right time to get started, the weight of the deadline to begin your migration to Drupal 10 has only grown heavier. After multiple extensions, the Drupal community has set January 5, 2025 as the final end-of-life date for Drupal 7.

What does that mean for your organization? On the one hand, you now have just over a year to start planning a migration before your site loses crucial support. But on the other hand, as many organizations like yours face a similar deadline, you can’t afford to wait much longer. The time to make the move to Drupal 10 is now.

Why you need to start planning for a Drupal 10 migration

If you’ve fallen behind in migrating your site from Drupal 7, you’re not alone. According to the Drupal community, more than 350,000 projects still use that version of the platform as of November 2023 — one-quarter of all Drupal sites.

As a result, you aren’t just facing a hard deadline to relaunch your new site as January 2025 grows closer. You’re also competing with a vast number of organizations just like yours who need to coordinate the same migration with a web development agency partner. Given that it takes an average of six months to complete the sales process to get started on a Drupal 7 migration, you’re already at risk of missing the deadline if you have not yet contacted an agency.

The longer you wait, the less likely you are to find a team with availability to work with you on a migration plan and website redesign before Drupal 7 reaches end-of-life. And, given the stakes involved, your organization can’t afford the risks of sticking on a platform without the vital benefits of ongoing support.

What your organization loses when Drupal 7 reaches end-of-life

Drupal 7 will reach its end of life 14 years after its initial release. If you’re still on the platform, your website will remain accessible after January 5, 2025. However, it will no longer receive feature updates, bug fixes, or security releases from the Drupal community.

This last detail is most critical to your organization. Any security issues discovered after January 2025 may be publicly disclosed, but Drupal will no longer provide any necessary updates. Prior to the announcement of this final extension for Drupal 7, your organization had the option of paying for extended support. But that is no longer the case.

When you work with the right agency partner, you can create a migration plan that will keep your website secure. Fortunately, your organization will be able to better manage ‌site security after the migration is complete. But that’s just one of the advantages made possible by getting your organization started with Drupal 10.

Drupal 10 offers dramatic advantages after migration

Trusting your site with the legacy code of Drupal 7 doesn’t just expose your organization to poor security. It prevents you from taking advantage of dramatic improvements for your site’s users and content editors.

Improved website speed and SEO performance

Fundamentally, your Drupal 10 website will run faster. Dynamic caching reduces page load times by invalidating only the content that has changed. Instead of needing to reload your entire page after a set amount of time, your cache can just reload the block with new information.

Drupal 10 also marks the end of Drupal 7’s jQuery. A large JavaScript library, jQuery was a powerful tool, but modern browsers perform many of the same functions. The up-to-date JavaScript used by Drupal 10 also decreases page load times.

Drupal 10 also supports new formats such as schema.org, Open Graph, and JSON-LD, which increase conversions from search engines. Plus, Drupal 10 supports advanced accessibility features that improve WCAG compliance and further improve SEO rankings.

Better site security and reduced maintenance costs

Drupal 10 improves your site security by including up-to-date protocols and dependencies such as PHP 8, Symfony 6, and CKEditor 5. As earlier versions of these dependencies reach end-of-life, they may be exposed to unpatched security vulnerabilities. Migrating to Drupal 10 avoids delays in getting critical security patches applied to your site.

One of Drupal’s major advantages as an open-source platform is the community’s Security Team, which delivers security advisories and provides guidance to contributed module maintainers on how to resolve potential vulnerabilities. Providing continued support from the community Security Team for all of your site’s contributed modules beyond the upgrade deadline is critical.

Improved content editing experience and efficiency

Drupal’s out-of-the-box CMS experience has always been limited. With Drupal 10, your site editors benefit from the Claro theme, which makes Drupal much easier to use. New image tools and an updated media library also enable better organization of your site’s assets.

Drupal 10 also includes the JavaScript text editor CKEditor 5, which further simplifies content creation and its accessibility. In addition, the platform offers enhanced translation capabilities in multiple languages, which enables your organization to reach a wider audience than ever.

Don’t wait until an emergency before moving to Drupal 10

Upgrading your site from Drupal 7 to Drupal 10 isn’t quick or easy. That’s why so many organizations like yours have been putting off the migration. But the sooner you start preparing your site for the future, the sooner you can take advantage of all Drupal 10 has to offer.

Better still, you gain the added peace of mind knowing your site won’t be exposed to critical vulnerabilities. And you don’t have to start planning on your own. With the right team of Drupal experts, you can make a plan to ensure your site remains stable and secure moving forward.

If this sounds like a plan that will help your organization move forward, we should talk.

The post Now’s the time to plan your migration to Drupal 10 appeared first on Four Kitchens.

cyberschorsch.dev: Elevating Drupal's Capabilities with Redis for Advanced Data Management

Most Drupal installations are using Mysql / MariaDB or Postgres for their data storage which allows Drupal to offer versatile and flexible ways of modeling content, especially building relationships with different content model, i.e. a blog post and a vocabulary with tags. In this blog post I will show you how to use Redis with Drupal for other things besides caching.

LostCarPark Drupal Blog: Drupal Advent Calendar day 6 - Smart Trim

Drupal Advent Calendar day 6 - Smart Trim james Wed, 12/06/2023 - 07:00 Image removed.

Welcome back to day 6 of the Drupal Advent calendar. Behind today’s door is the Smart Trim module, and here’s Mark Casias (markie) to tell us all about it.

Smart Trim allows you to control the length of your content by trimming it intelligently. It is designed to be a focused, lightweight improvement over Drupal core’s current formatter trimming capabilities. The maintainers’ focus is stability and ease-of-use. Customizations to the module are encouraged with template overrides and Smart Trim hook implementations.

After installing and enabling Smart Trim, you will see a “Smart trimmed” option in…

Tags