The Drop Times: Christina Lockhart on Elevating Drupal: The Essential Role of Women in Tech

Discover how women are transforming the Drupal community and driving innovation in technology. In this interview, Christina Lockhart, Digital Marketing Manager at the Drupal Association, shares her journey, her key responsibilities, and the vital role women play in advancing Drupal. Learn about her strategies for promoting DrupalCon, her insights on overcoming barriers for women in tech, and the importance of empowering female leaders in the industry.

Nonprofit Drupal posts: June Drupal for Nonprofits Chat

Join us THURSDAY, June 20 at 1pm ET / 10am PT, for our regularly scheduled call to chat about all things Drupal and nonprofits. (Convert to your local time zone.)

We don't have anything specific on the agenda this month, so we'll have plenty of time to discuss anything that's on our minds at the intersection of Drupal and nonprofits.  Got something specific you want to talk about? Feel free to share ahead of time in our collaborative Google doc: https://nten.org/drupal/notes!

All nonprofit Drupal devs and users, regardless of experience level, are always welcome on this call.

This free call is sponsored by NTEN.org and open to everyone. 

  • Join the call: https://us02web.zoom.us/j/81817469653

    • Meeting ID: 818 1746 9653
      Passcode: 551681

    • One tap mobile:
      +16699006833,,81817469653# US (San Jose)
      +13462487799,,81817469653# US (Houston)

    • Dial by your location:
      +1 669 900 6833 US (San Jose)
      +1 346 248 7799 US (Houston)
      +1 253 215 8782 US (Tacoma)
      +1 929 205 6099 US (New York)
      +1 301 715 8592 US (Washington DC)
      +1 312 626 6799 US (Chicago)

    • Find your local number: https://us02web.zoom.us/u/kpV1o65N

  • Follow along on Google Docs: https://nten.org/drupal/notes

View notes of previous months' calls.

Specbee: Getting started with integrating Drupal and Tailwind CSS

If you’re tired of spending hours tweaking CSS stylesheets to get your website looking just right, then you should consider a new way of CSS’ing (yeah, we just made it up). We’re talking about Tailwind CSS - a different way of doing CSS. It uses a utility-first approach, which means instead of creating a class for a component, let’s say a button, you would use a pre-defined class that’s built to style the button, like a “font-bold” or a “text-white”. All of this right from the comfort of your HTML!  Couple Tailwind CSS, a sleek, utility-based open-source CSS framework, with a modular, highly customizable, and modern CMS like Drupal 10, and you have a powerhouse combination!  In this article, we’ll be talking about Drupal and Tailwind CSS AND how you can integrate them seamlessly to build modern, responsive, and visually stunning websites Why Drupal is a good choice for web development Drupal is an open-source content management system (CMS) that has been gaining popularity among web developers for its versatility and powerful features. The latest version, Drupal 10 brings a host of new features and improvements meant to simplify development and enhance user experience. 1. Highly customizable design: One of the biggest advantages of using Drupal is its highly customizable design. With a wide range of themes and templates available, developers have the freedom to create unique and visually appealing websites that cater to their client's specific needs. 2. Flexibility and scalability: Drupal's modular architecture makes it incredibly flexible and scalable, making it suitable for building websites of any size or complexity. It offers a vast library of modules that can be easily integrated into your website, providing additional functionality such as e-commerce capabilities, social media integration, multilingual support, and more. 3. Robust security measures: Security is a major concern in today's times; hence it is crucial to choose a CMS that prioritizes it. Drupal has always been recognized as one of the most secure CMS platforms due to its stringent security standards and frequent updates that address any potential vulnerabilities promptly.  4. SEO-friendly: Search Engine Optimization (SEO) is vital for every website's success as it determines its visibility on search engines like Google. Drupal's built-in SEO tools assist developers in optimizing their websites by generating search engine-friendly URLs, meta tags, and sitemaps, and providing customizable page titles and descriptions. 5. Active community support: Drupal benefits from a substantial and engaged group of developers who contribute to its ongoing evolution and offer support to fellow users. This community-driven approach ensures that any issues or bugs are addressed promptly, and new updates and features are released regularly. Why Tailwind CSS is great for web developers Tailwind CSS has gained immense popularity in the web development community due to its numerous benefits and advantages.  1. Highly customizable: One of the biggest advantages of Tailwind CSS is its high level of customization. Unlike other popular front-end frameworks like Bootstrap or Foundation, Tailwind does not come with predefined styles and components. Instead, it provides a comprehensive set of utility classes that can be used to create custom designs according to your specific project needs. This allows developers to have complete control over their designs and enables them to create unique and personalized user experiences. 2. Lightweight: Another major benefit of using Tailwind CSS is its lightweight nature. Since it only generates the required classes based on your design choices, it helps keep the file size small and improves website performance. This is especially beneficial for Drupal websites which often have heavy content and functionality that can slow down page loading speed. 3. Mobile-responsive: With more people accessing websites through mobile devices, having a mobile-responsive design has become crucial for any website's success. The use of Tailwind CSS makes it easier to create responsive designs without adding extra code or media queries. Its mobile-first approach ensures that your website looks great on all screen sizes without compromising on performance. 4. Faster development process: By eliminating the need for manually writing complex CSS rules, Tailwind speeds up the development process significantly. It also reduces the chances of errors as developers can easily reuse existing utility classes instead of creating new ones from scratch every time they need a similar style element. 5. Scalable designs: With Tailwind CSS, you can create scalable designs that are easy to maintain and modify in the long run. As your website grows and evolves, making changes to its design becomes more manageable with Tailwind's utility classes, as opposed to traditional frameworks where modifying styles can be a tedious process. Why Integrate Drupal with Tailwind CSS? One of the main reasons to integrate Drupal with Tailwind CSS is its ability to simplify web development. With Tailwind CSS, developers can avoid writing repetitive and lengthy code for styling. Instead, they can use pre-built classes that provide consistent and reusable design patterns. This not only saves time but also results in cleaner code that is easier to maintain. Another benefit of integrating Drupal with Tailwind CSS is its responsive design capabilities. With the increasing use of mobile devices, it has become essential for websites to be optimized for all screen sizes. Thanks to Tailwind's built-in responsive utilities, designers can easily build responsive layouts without having to write separate media queries for different devices. Step-by-Step Guide to Integrating Drupal with Tailwind CSS Step 1: Get your prerequisites ready Local Drupal Setup NPM and Yarn package Managers Drush Lando Step 2: Create a custom theme We will begin by creating a Drupal custom theme and then will integrate Tailwind CSS into the same. In this tutorial, I am using the starter kit theme command to generate my custom theme. Go to the web directory and type in the following command in the terminal php core/scripts/drupal generate-theme drupal_tailwind_theme after pressing the enter key our custom theme will be generated as shown below: Next, we will generate the package.json file which we require to initialize a new node.js project. Go to the terminal and type in the following command npm init and it prompts us with a series of questions regarding our project since for this tutorial I am keeping everything default by pressing the enter key until our package.json file is added as shown in the image. Step 3: Install and set up Tailwind CSS Now let’s install Tailwind and its dependencies and also configure it. In the terminal, run the following command:npm install -D tailwindcss postcss autoprefixer Next, let’s generate a Tailwind CSS config file using the following command:npx tailwindcss init -p Go to the tailwind.config.js file and set the path for Tailwind to scan. Since our Twig templates are in the templates directory, we will use that path as shown in the image. Now we need to create a CSS file to put the Tailwind directives in. Go to the src folder, create a file named index.css, and paste the following directives:@tailwind base;@tailwind components;@tailwind utilities;   Create a folder where the Tailwind CSS will be compiled. On the same level as the src folder, create a folder named dist (or any name you prefer). We now run the following command:npx tailwindcss –input src/index.css –output dist/index.css After executing this command, we will be able to see the compiled version of the Tailwindcss in the dist folder. We can verify it by going to the dist folder as shown in the image. In the package.json file, we will be adding the scripts dev and watch which can be executed using npm run dev & npm run watch or using yarn dev & yarn watch. The script dev compiles the code once as per command while the watch command keeps a watch on any change. Step 4: Adding Tailwind CSS to our Drupal Theme Now we will be adding Tailwind to our Drupal site. For that, we can add a library namely tailwind, and give it a CSS path of the dist/index.css. That means where we have our compiled tailwind. Next, we can add that library either globally or to the specific template. For the purpose of this tutorial, I will be adding it globally. Using Tailwind CSS in our Drupal theme For this tutorial, I am using the page.html.twig file and adding a red background color by including the class bg-red-500 in the markup. Clear the cache and check the output. Our Tailwind CSS class has applied the desired background color.   Final Thoughts Tailwind CSS is a great choice when you want to build websites quickly and easily. It integrates well with Drupal and the combination of these two tools creates a powerful synergy for web development. Reach out to us if you would like to learn more about how Specbee’s Drupal experts can help you create stunning web experiences with Drupal and Tailwind CSS.

Talking Drupal: Talking Drupal #455 - Top 5 uses of AI for Drupal

Today we are talking about AI Tips for Drupal Devs, AI Best Practices, and Drupal Droid with guest Mike Miles. We’ll also cover AI interpolator as our module of the week.

For show notes visit: www.talkingDrupal.com/455

Topics
  • Top 5 tips
    • Idea Generation (Ideation)
    • Code Generation
    • Debugging
    • Content Generation
    • Technical Explanations
  • How do you suggest people use AI for Ideation
  • Is MIT Sloan using AI to help with Drupal Development
  • Does that code get directly inserted into your sites
  • What are some common pitfalls
  • Is your team using AI for debugging
  • Any best practices you have found helping when working with AI
  • Is MIT Sloan using AI for content generation
  • What is an example of how you use AI for technical explanations
  • What is your view ont he future of AI in Drupal, do you think AI will replace Drupal developers
Resources Guests

Michael Miles - mike-miles.com mikemiles86

Hosts

Nic Laflin - nLighteneddevelopment.com nicxvan John Picozzi - epam.com johnpicozzi Randy Fay - rfay

MOTW Correspondent

Martin Anderson-Clutz - mandclu.com mandclu

  • Brief description:
    • Have you ever wanted to use AI to help populate entity fields that were left blank by Drupal content authors? There’s a module for that.
  • Module name/project name:
  • Brief history
    • How old: created in Sep 2023 by Marcus Johansson of FreelyGive
    • Versions available: 1.0.0-rc4
  • Maintainership
    • Actively maintained, recent release in the past month
    • Security coverage - opted in, needs stable release
    • Test coverage
    • Documentation - User guide
    • Number of open issues: 18 open issues, none of which are a bugs
  • Usage stats:
    • 94 sites
  • Module features and usage
    • In scientific fields, interpolation is the process of using known data to extrapolate or estimate unknown data points. In a similar way this module helps your Drupal site provide values for fields that didn’t receive input, based on the information that was provided.
    • Fundamentally Interpolator AI provides a framework and an API, and then relies on companion modules for processing, either by leveraging third-party services like AI LLMs, or PHP-based scripting.
    • There are existing integrations with a variety of AI services, including OpenAI, Dreamstudio, Hugging Face, and more.
    • You can add retrievers to help extract and normalize the content you’re processing, for example photos from an external site, and other tools to help normalize and optimize content and media, and optimize any prompts you will be using with AI services.
    • You can also extend the workflow capabilities of AI Interpolator, for example using the popular and powerful ECA module that we’ve talked about before on this show.

The Drop Times: Tech Talks, Brand Strategies, and the Future of Drupal: Highlights from The DropTimes

An enterprise web solution is inherently complex. Its endless integrations with various applications that are added or loaded off as per the changing requirements, multiple front-ends that provide varied and personalised digital experiences, the cultural nuances catered to in its l10n editions, the time-zone differences that are to be taken care of, etc., etc., are the most basic parts that add to the complexity.

Continuous investment, development and deployment are part and parcel of such a solution. Even so, it becomes amiable only if the complexity is masked out in the simplicity of the consumer touch points.

Two separate sets of consumers should be considered there. One is the enterprise consumers, the content creators and marketers, who are the immediate benefactors of the solution. The second, a more prominent set, is the customers to whom the enterprises cater.

Drupal, the platform for building a digital experience, invested heavily in satisfying the end customers. That was what Drupal agencies were doing all these years. They got an exoskeleton on which they built the end-user experiences. But what about the enterprise consumers themselves? Weren’t they the ones who ultimately decided to ditch or continue using the services? How good were their experiences sans the involvement of a hired developer?

The decision to simplify the touch points of enterprise consumers is a development and design decision. These content creators and marketers will benefit the most from the Starshot Initiative. It supports the marketing team by reducing the go-to-market time and eases the content creators by providing the most valuable tools out of the box. A complex solution is now draped in a simple cassock.

The first story I’m sharing today concerns Drupal’s new brand strategy and future directions. The Starshot Initiative manifests this strategy and the direction the project is taking. An interview with Shawn Perritt, Senior Director of Brand & Creative at Acquia, shines a light on this brand refresh. Read Shawn’s conversation with Alka Elizabeth, our sub-editor.

Montreal became the hub for tech talks in the past week. We conducted one-question interviews with three featured speakers at Evolve Drupal Montreal. Kazima Abbas, our sub-editor, spoke with Josh Koenig, co-founder of Pantheon, Joe Kwan, Manager of Web Development at the University of Waterloo, and the formidable Mike Herchel, Senior Front-end Developer at Agileana. Their answers form part of the feature published here.

Kazima also conducted an exclusive interview with Baddý Sonja Breidert, CEO and Co-Founder of 1xINTERNET. The interview focused on the agency’s support for the Starshot Initiative based on its experience with ‘Try Drupal’, which implements a default Drupal deployment for enterprises. It explains why they did not wait or hesitate to offer all-out support for the new initiative.

Alka Elizabeth and Ben Peter Mathew, our community manager, had jointly covered the Starshot Session on ‘Strategic Milestones in Product Definition’ led by Dries Buytaert and Cristina Chumillas on June 7. The report can be read here.

The next two stories are our signature stories, written by our founder and lead, Anoop John, CTO of Zyxware Technologies. From the start, Anoop was vocal about ‘DrupalCollab’, an idea he had been nurturing for years. As part of the initiative, he has published a list of the largest 500+ cities in the world with a sizable population of people tagged ‘Drupal developers’ on LinkedIn. You can read the analysis here. The second story published with this list is, On Using LinkedIn to Analyze the Size of the Drupal Community, an article on the methodology for this analysis using LinkedIn, associated errors and justifications. Based on these stories, Anoop is trying to build momentum to restart local Drupal meetups in as many cities as possible. Also, read his LinkedIn article on the initiative here.

Mautic 5.1 Andromeda Edition was released last week with major updates. Read our report here. We published a quick review of the Drupal Quick Exit Module developed by Oomph Inc. Ben Peter Mathew spoke with Alyssa Varsanyi of Oomph to produce this report.

To ensure brevity, I shall list the rest of the important stories below without much ado.

That is for the week, dear readers. I wish you all a very sacred Eid Ul Adha. Let the festival of sacrifice be a time to ponder the things we are ready to give up for the better common good.

To get timely updates, follow us on LinkedIn, Twitter and Facebook. Also, join us on Drupal Slack at #thedroptimes.

Thanks and regards.

Sincerely,
Sebin A. Jacob,
Editor-in-Chief, The DropTimes

ADCI Solutions: How to add a live chat to a website using Mercure

<p>We are currently working on a platform for contacting influencers and media to promote products, services, and personal brands. As the platform was developing, the client felt the need to <a href="https://www.adcisolutions.com/work/mercure-chat?utm_source=planetdrupal%26utm_medium=rss_feed%26utm_campaign=mercure_chat">add live chat functionality</a> so that platform clients could communicate with its administrators and copywriters. But it had to store its history on the client server.&nbsp;</p><img data-entity-uuid="8baeedd5-7f77-4fad-af7b-78aba79bfae1" data-entity-type="file" src="https://www.adcisolutions.com/sites/default/files/inline-images/adding-a-live-chat-to-website.png" width="1324" height="842" alt="adding a live chat to a website">

Mario Hernandez: Image styles in Drupal

Now that we've gone over some very important concepts of responsive images (art direction and resolution switching), it's time to transfer all that knowledge and put it all in practice in Drupal. One of the key pieces for achieving responsive images in Drupal is by using image styles. Image styles are how Drupal manages the way we crop and size images.

What are image styles?

Before we get to building image styles, let's go over what they are. Think of image styles as templates for cropping, scaling, converting, and sizing images. You can use these templates with any image on your site and as many times as you'd like. Thanks to image styles images will always render within the parameters we define.

A more real-world way of looking at image styles may be if you could imagine for a moment you have a couple of picture frames you'd like to use to hang some pictures in your house or office. One frame is 5x7, another is 4x6 and one last one is 8x10. The picture frames are Drupal's image styles.

So we have some picture frames and we have ordered several pictures from our favorite online photo printing service. There is one picture in particular I really love and I want to frame it using the 3 picture frames. So, although it is the same picture, I ordered different sizes of it (one for each frame size), and this will allow me to hang the 3 pictures in different sizes, aspect ratios and orientation. That in a nutshell are image styles.

Image removed.

Image styles best practices

Image styles are actually pretty easy to create but unfortunately because of this they can be misused or mismanaged. If not done properly, you may end up with a lot more image styles than you really need or image styles that are not well define and do no provide the outcome you are looking for. To avoid this, let's go over best practices for creating image styles which will result in less image styles to manage. Mind you, these are my best practices but I have to admit, they have worked very well for me.

Naming image styles

Have you heard the phrase "naming things is hard"? It's true. Unfortunately when it comes to image styles, if not named properly you can get yourself in a lot of trouble. Quick example, let's say I want to create an image style that I'd like to use on images of news articles that are displayed on the homepage. One might think a good name for the image style may be something like "Homepage news article images". It doesn't seem so bad but let me point out a few issues with this name:

  • The image style is limited to the homepage
  • It is limited to news article images
  • It lacks information about the image dimensions or aspect ratio

One objective with image styles is to create them in a way that they are reusable. The more reusable an image style is the less image styles you will need to create which in turn becomes easier to manage. The main issue with the image style above ("Homepage news article images"), besides the 3 bullet points we called out, is that is not reusable. The name of it limits us to only use it on the homepage and only for news article images. If we want to display similar images elsewhere, we would need to create another image style maybe with the same parameters as the first one. You may be asking yourself, wait, why can't we use the same image style elsewhere? Technically you can, but think about how confusing it will be to use an image style called "Homepage news article images", not on the homepage and not on news article images.

Creating reusable image styles

One very efficient way for creating reusable image styles is to name them based on the image aspect ratio or dimensions, or a combination of both. For example: "16:9 (Max 320px)", or "Box 1:1 (500px)". Here are some reasons why this is a great way to name image styles:

  • They are not specific to any page or type of image (articles, events, etc.)
  • They provide key information about the image aspect ratio and their dimensions
  • I can use these image styles hundreds of times on any image that fits the requirements as well as on any page
  • By creating/naming image styles this way, I may have just saved myself from creating many other image styles

Identifying the images patterns

I have found one of the most effective ways for identifyiing the image styles you need to create is by looking at your website mockups (if you are fortunate enough to have them). This may not always be possible, but if you do have designs for your website, this will tell you exactly which images you will need and how they need to be rendered. Having this information upfront will help you tremendously when creating image styles because you can plan ahead of time how to create reusable image styles that share commom attributes.

Image styles use cases

When naming image styles it helps me to think of the characteristics of the images I am creating image styles for. For example, I have an image that should be rendered in 16:9 aspect ratio and it should not exceed a width of 320px. This is how I arrived at the name 16:9 (Max 320px). This also makes it possible to know which image style to use if I have other images that need to be rendered similarly. By the way, it is perfectly okay to use an image style that is slightly off from what an image needs to be rendered at. For example, Let's say I have an image that should be rendered at 16:9 aspect ratio, but its size should not exceed 250px. for this image, I can still use the 16:9 (Max 320px) image style.

A 100px or even 200px difference between the image style dimensions and the image you need to use it on it's an acceptable thing to do for a couple of reasons:

  • 100 or 200px in most cases will not make a big of an impact in performance, however, if you are rendering 50 of these images in a single page, then this could certainly present performance issues. So my rule is as long as this is a oneoff type of situation, I'm okay with doing this.
  • Keep in mind that just because your image may be resized larger than it actually needs to be rendered, your image will still visually rendered at the right size as I would suppose it is inside a container that will be sized to the right rendering size, via CSS.
  • Being able to reuse an image style that may be slightly larger than needed saves me from creating more image styles.

I hope you see the impact good names for image styles have on your site. When you are working on an enterprise level website, using the best practices above can really help you with the maintenance of your image styles.

Image styles effects

Effects are the rules you set on each image style. Rules such as cropping, sizing, converting, saturating, rotating, and scaling of images is how we determine how to render the images in our site. In most cases, you want to let content creators of your site upload images that are relatively big. Doing so will allow you to use the images in your library in any use case. It is perfectly okay to scale your images down thorugh the use of image styles, but it is not recommended to scale images up. Doing so will result in blurry or pixelated images. This is why is better to upload large images. But you may be thinking, if I upload super large images, this will affect the performance of my site. It will if you are rendering the original images, but since we are using image styles, Drupal uses the original image to make copies at the size and aspect ratio you defined in your image styles. This is why by uploading a single image you are able to use it in many use cases at different sizes or aspect ratios.

Image styles effects can vary from image style to image style. For example, some image styles will require images to be scaled down, then cropped. Others will require images to be resized then cropped and others may just need for images to be resized to specific size. All these actions are called "Effects" in image styles. The effects you apply to your image styles will depend on the end goal for rendering the images. Let's do a quick demo of creating one image styles then applying effects to it.

Hands-on excercise

All the principles covered in this series apply to Drupal 8, 9, and 10. You can follow along or simply watch me do it. To get started, spin up a vanilla Drupal site of the version of your choice. At the begining of this series I mentioned we will stick with only core/out of the box functionality to keep things simple.

Creating a new image style

  1. Login to Drupal as administrator
  2. In your Drupal site navigate to /admin/config/media/image-styles
  3. Click Add image style
  4. For Image style name type: 16:9 (Max 320px)
  5. To keep things nifty, edit the image style machine name so it reads 16_9_max_320px. (Remove the trailing underscore generated by the ending parenthesis in the image style name. Clean machine names are important to me 😃. It actually makes a difference when you are debugging issues and you find your machine name has an extra underscore you didn't catch).
  6. Click Create new style

Image removed.

The image style above follows the best practices for name we covered earlier. This makes this image style reusable on any image that meets the aspect ratio and dimension requirements.

Adding effects to the image style

For the purpose of this exercise, we are going to use the Scale and crop effect. This is probably the effect I use the most because it does exactly what I want, scale the image down to the size I want and crop it in the aspect ratio I need.

  1. While in the page where the new image style was created (/admin/config/media/image-styles/manage/16_9_max_320px), scroll down and you should see the Effect dropdown
  2. Select Scale and crop from the dropdown
  3. Click Add. The Add Scale and Crop effect screen will come up
  4. Type 320 for width and 180 for height. Note: These two values are required when you select the scale and crop effect. In other effects, these values may not always be required. It is important to define fixed dimensions on your image styles. This ensures your images will be sized/cropped at exactly the size you expect them to. How did I figure out the height for a 16:9 image with a width of 320px is 180px? I used this online aspect ratio calculator.
  5. Notice how you can change the focal point of the cropping by clicking any of the circles under Anchor. For this example we'll keep it in the middle circle.
  6. Click Update effect. This will bring you back to the image style page.
  7. We're done!

Image removed.

Now we have one custom image style with specific effects. If you noticed, Drupal comes with a couple of predefined image styles. If they work for your images you should make use of them. In this series we will be creating custom image styles.

As I mentioned earlier, names of image styles should be descriptive but not limiting. In the case of some of the image styles that come out of the box with Drupal, the names Large, Medium, and Wide do not seem like good choices for names because those names are all relative. Large in relation to what? Medium in relation to what? ...just sayin'.

Image multipliers

One thing we have not discussed but it is very important in responsive images, is the use of "Image Multipliers". What are image multipliers? In responsive images, you often think of image sizes in natural dimensions. If I think of an image that needs to be rendered at 720px, I will most likely resize or crop that image at 720px which makes total sense. With the evolution of high density or high resolution (retina) screens on mobile and larger devices, because they contain thousands or millions more pixels than traditional resolution screens, images need to actually be bigger than the intended size so they are rendered at their highest resolution/quality. This is what image multipliers are.

If we go back to the example above of the 720px image. For this image to be rendered as sharp and high-quality as possible in retina screen devices, we should add a 2x or 3x multiplier to it. Meaning, we should create an image styles for this image at twice and three times the intended size (1440px, 2160px). When we do this, the image will still be rendered at 720px (visually), but because we are providing larger images, these images will have twice or three times the number of pixels within them and when viewed in high resolution screens, the image quality will be superior than if we are only providing a regular 720px image. Note: I typically only create a 2x multiplier image styles for most of my images, but there may be situation when there are specific requirements for creating a 3x multiplier image styles.

Create a 2x multiplier image style

The same way you created the original image style above for 16:9 (Max 320px), go ahead and repeat the process but this time create a 2x multiplier image style, 16:9 (Max 640px). Remember, the dimensions of this image style should be 640 x 360px.

So what's next?

With our custom image styles in place, we can now make use of them, but before we do, let's go over another very important concept within Drupal, Responsive image styles ...whaaaaatttt?
We'll comeback to Drupal in a bit but first, we'll talk about responsive image styles in the next post.

Navigate posts within this series

Mario Hernandez: Image resolution switching using srcset and sizes attributes

In the previous article we defined what art direction is and how to address it using the <picture> element. In this post, the focus will be how to address responsive images when the requirement is image resolution switching. Resolution switching, in the context of responsive images, is rendering identical image content on all devices. Unlike art direction where each device gets a differently cropped image that may vary on aspect ratio, resolution switching uses images that are simply larger or smaller based on the device but retain the same aspect ratio and cropping settings. Resolution switching is how most images are rendered (the rule), the <picture> element approach is the exception to the rule. Take a look at an example of resolution switching below.

Image removed.

The image above demonstrate how multiple resolutions of the same image can be served to different devices. All the images in the example above are cropped exactly the same maintaining the same aspect ratio from large to small.

Using srcset and sizes attributes

Using the srcset and sizes image attributes is how most images are rendered in the web today. As indicated before, this is the recommended way for configuring responsive images if all you need is to switch resolution of images rather than art direction. So how does this approach work? Let's take a look at a typical configuration of the <img> tag using the image above as an example of the different image sizes we will want the browser to choose from:

<img srcset="original-image.jpg 2400w, extra-large.jpg 2000w, large.jpg 1600w, medium.jpg 1080w, small.jpg 800w, x-small.jpg 500w" sizes="100vw" src="large.jpg" alt="Image of sky shown at different resolutions" />

Let's break things down so we can understand this approach better.

  • <img>: Right off the bat we start by using a widely supported html tag.
  • srcset: The srcset attribute in the img tag serves two important roles, 1) It stores a list of images that can be used by the browser, 2) Each image provides its width value which plays a role on the browser choosing the right image.
  • sizes: The sizes attribute tells the browser the width, in relation to the viewport, the image should be rendered at. The value of 100vw shown above, means the image will be rendered at 100% the viewport width on all the devices. You could also use media queries like (max-width: 720px) 100vw, 50vw. This means that if the device does not exceed 720px in width, the image will be rendered at 100% the viewport width, otherwise (if the device is larger than 720px), the image will be rendered at 50% the viewport width.
  • src: The src attribute is used as a fallback if everything fails.

What does it all mean?

Let me explain things in more detail because it is important we understand how this approach is so much better than using the <picture> element.

The biggest difference/advantage of using srcset and sizes versus <picture>, is the fact that we let the browser decide which image is the best image to render on any device. This is possible thanks to all the information we have supplied to the browser. For example, in the srcset we are not only providing the browser with a list of images to choose from, but we are also telling the browser how big each image is. This is very important because the browser will use this information when choosing the image to render. In the <picture> element approach, the image size descriptors are not available.

The sizes value tells the browser the size the image needs to be rendered at in relation to the viewport. This too is extremely important information we are providing the browser because if the browser knows the dimensions of all the images to choose from and how big/small the image needs to be rendered, then the browser is able to pick the best image possible.

But that's not all, the browser is smarter and knows more about the web environment than we do when a page or image is rendered. For example, the browser knows the viewport width used when viewing a website, it knows how fast/slow your internet connection is, and it knows about any browser preference settings (if any), setup by the user. Using all this information the browser is able to determine which image from the srcset is the best to use. In contrast, with the <picture> element, we tell the browser which image to use solely based on the device size.

Closing the gap

Now let's see how using the srcset and sizes attributes closes the gap we identified when using the <picture> tag.

Environment conditions What the developer knows
during development What the browser knows
during image rendering Viewport dimensions No Yes Image size relative to the viewport Yes No Yes via sizes Screen density No Yes Images dimensions Yes No Yes via srcset

Pretty nice huh? Now thanks to the srcset and sizes attributes we've closed the gap and the browser has all the information it needs to ensure the best image is served to each device.

The next post of this series will focus on image styles. These are fun but can also get you in a lot of trouble if not properly done. See you there.

In closing

Time for a story: I recently did an experiment that 100% proves the use of resolution switching using srcset and sizes attributes. As most people nowadays, I use a very large second display when working on projects to fit more apps and see things better. My second display is nice but it's not a 4K display. It's double the physical size of my mac's screen, but the mac's screen resolution is higher by almost double (twice the number of pixels). When I look at an image of a project where I've implemented the practices in this guide, in the large display, and inspected the page, I see the browser has selected an image that is 720px which makes complete sense for the use case I am testing. I then unplugged the second display and viewed the page on my mac's screen (higher resolution), I reloaded the page and inspected it, I noticed the browser has now selected an image that is double the size of the first image. This is exactly the behavior I would expect because my mac screen is of higher resolution and my connection speed is very fast. So the browser was able to make the smart decision to use a different images based on my environment.

Navigate posts within this series

Mario Hernandez: Drupal base path

Recently I was building a component that required a static image which was not stored in the database but instead needed to be stored somewhere in the file system of the site. There are several ways for serving a static image for example we could have stored the image in the sites/default/files/images/ directory. A very common approach which in many cases would work just fine, however, in my case I was building a component and I wanted for the component image to be located within the same component's directory. This makes sense because if I wanted to reuse or share this component, all component assets would be included in a single directory.

Requirements

My goal with this task was to dynamically point to the image regardless the site this component was running on. Oh yeah, we are running a multi-site architecture with hundreds of sites and a single code base. So this component needed to work in all of these hundreds of sites. Now the challenge seems a little more... "challenging".

¡Manos a la hobra'!'

I started by doing research to determine the best way possible to achieve this. I read about using a pre-process function that would generate a dynamic base path of the site but I was hoping I could keep things simple and do everything on the front-end with only Twig. This would make it a more appealing approach for front-end developers.

After some research, I came across two little gems that became game-chargers for my project. One of these gems is the {{ url('<front>') }} Twig function. This will provide the current site's homepage/base path. The other very handy Twig function is {{ active_theme_path() }} which prints the path of the current active theme (themes/custom/my_theme). While researching for this task, I also found you can use the {{ directory }} Twig variable in your theme's templates to print the active theme's path. A word of coution when using either the {{ active_theme_path() }} function of the {{ directory }} variable as these could have different results depending on your whether you are using them in a base or sub theme. Here's a drupal.org issue that discusses this in more detail.
Armed with these two little functions, and one Twig variable, we can now work in generating a dynamic path to our theme's directory where the static image for our component is located. So this may seem like a simple thing but remember, our component's image should work regardless of the site the component is used on within our multi-site architecture. Some sites even use a different sub-theme but the parent theme is always the same which is where our image is stored.

Building the dynamic path

Before we can use the first function we need to run it through the |render Twig filter. Since Twig will return an array from the {{ url() }} function, we need to convert it to a string because we need the value of the function. Let's take a look:

{{ url('<front>')|render }} # This will give us http://my-site.com/

Next let's work with the theme path function. Similarly to the function above, we will use the |render Twig filter to convert it from an array to a string.

{{ active_theme_path()|render }} # This will give us themes/custom/my-theme

Now that we have two strings we can joint them together to compose the full path to our image:

<img src="{{ url('<front>')|render }}{{ active_theme_path()|render }}/images/image.jpg" alt="alt text" />

If we want to get fancy we could actually set a variable to shorten things a bit:

{% set theme_url = url('<front>')|render ~ active_theme_path()|render %} <img src="{{ theme_url ~ '/images/image.jpg' }}" alt="alt text" />

And there you have it. A dynamic path that will work on any of our sites.

I realized some people reading this already knew all of this but I didn't. So I figured I would share it because I bet there are others out there that also do not know about the {{ url('<front>') }} or {{ active_theme_path() }} Twig functions as well as the {{ directory }} variable. As I said before, there are many ways to handle this challenge, but in my case this is exactly how I wanted to approachh it. I hope this was helpful. Cheers!

Mario Hernandez: Responsive image styles

In a nutshell, responsive image styles are a collection of image styles. It can be confusing because the similarities in their names, but responsive image styles are a bundle that holds one or more image styles.

What's the use of responsive image styles?

If you read the posts about the <picture> element as well as the one about srcset and sizes attributes, we discussed that whether you are doing art direction or resolution switching, we need to provide the browser with a collection of images to serve to different devices. In Drupal the way we provide the collection of images is by using responsive image styles.

Image removed.

Naming responsive image styles

In the previous post we went in detail about best practices for naming image styles. Properly naming responsive image styles is just as important but there are some differences in guidelines. While naming image styles is mostly based on the characteristics of the images (aspec ratio, orientation, dimensions), naming responsive image styles is typically based on their use case. Let's take a look at some examples.

Let's say we are building a photo gallery where we will use a series of images to display as a slider or photos grid. We may not be as concerned about the images aspect ratio or dimentions because we already have image styles in place to handle that. We're only interested on how the images will be used. In this example the use case is a Gallery. So a name for the responsive image style that makes sense to me would be Gallery or Photo gallery. Another example would be creating a responsive image style for your website's hero component. Regardless of what the images dimensions are, the responsive image style can be called Hero. Both of these examples are for very unique use cases, but there are also cases for more common type of responsive images styles such as a listing of news articles or events, a featured news article or a page for team member photos. In these cases, we can use names that we can reuse elsewhere. Something like Person listing, News full, Content grid, or 16:9 (Max 460px).

Back to hands-on exercises

We are going to create a new responsive image style in which we will make use of the image styles we created in the previous post. Let's pretend the images we are targeting will be used for displaying News and Events listings (Similar to this, and example below).

Image removed.

Most websites use patterns that they repeat across their sections or pages. The news listing example above is a pattern that can be used for not only displying news articles, but maybe also events, social media posts, and more. This is great because identifying these patterns can help us create better image styles and responsive image styles that are reusable. This is what I meant in the previous post when I said that if you are fortunate enough to have designs for your project, you will be able to identify these patterns right away. Let's keep this in mind as we get back into exercise mode.

Resolution switching

Here's where all of our knowledge about <picture> (art direction) and srcset and sizes (resolution switching) comes in handy. We'll start with resolution switching because art direction requires additional tooling and configuration.

In Drupal 8 we used the Picture and Breakpoints contrib modules to handle responsive images. Starting with Drupal 9, Drupal provides the "Responsive image" core module which means we don't need to install any contrib modules. Responsive image is not enabled by default.

  1. Enable the Responsive image core module (/admin/modules)
  2. Once enabled, head over to /admin/config/media/responsive-image-style to begin creating our first responsive image style
  3. Click Add responsive image style
  4. Type Content grid as the label for the responsive image style
  5. Select *Responsive image from the Breakpoint group dropdown
  6. Scroll down and select a Fallback image style (16:9 (Max 320px))
  7. Expand the 1x Viewport Sizing [] fieldset
  8. Under Type, chose Select multiple image styles and use the sizes attribute
  9. Under Sizes type the following: (max-width:640px) 100vw, 30vw (I'll explain shortly)
  10. Under Image styles select the image styles we created before
  11. Scroll down and click Save

Image removed.

Let's go over everything we just did

Since we are doing resolution switching and not art direction, we chose Responsive image from the Breakpoint group dropdown. Doing so presents to us the 1x Vieport Sizing [] screen with the following options:

  • Type: Again, since we are doing resolution switching, the obvious choice here is Select multiple image styles and use the sizes attribute. The other two options are irrelevant in this particular example.
  • Sizes: The Sizes option is where we tell the browser how big/small our images should be rendered in relation to the viewport being used. Depending on our goal, this field accepts a single value or a media query with some conditions. Let's say we wanted our images to always render at full width regardless of the device being used (like a Hero image for example), then the value for the Sizes field would be 100vw (100% the viewport width). In our case however, we want the image to display full width, but only if the viewport/device is not larger than 640px, otherwise, meaning if the viewport/device is larger than 640px, we want the image to display at 30% the viewport width. We could had also used a pixel-based value such as 400px for example.
  • Image styles: This is where we choose the image styles we want to make available for the browser to pick from. Think of this as the srcset attribute in the <img> tag.
  • Fallback image: We pick a fallback image in case all the above fails.

Very important: Remember in the Image resolution switching using srcset and sizes attributes post, our claim was that it's better to let the browser pick the best image possible as the browser is smarter than us? This is exactly what we are doing here. We are providing the browser with a collection of images to pick from. Each image provides its dimensions. Then we tell the browser how big/small we want the images to be rendered. One thing we are not doing is telling the browser which image to use, we let the browser make that decision. This is the complete opposite of what we do when we use <picture>. As a reminder, the method used above is what you would do in most of your images. This is like the default configuration for your responsive images. Only when you need to crop your images differently for each device size is when you would use the art direction approach.

Navigate posts within this series