Modernizing Drupal 10 Theme Development - Luca Lusso - E-Book

Modernizing Drupal 10 Theme Development E-Book

Luca Lusso

0,0
28,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Working with themes in Drupal can be challenging, given the number of layers and APIs involved. Modernizing Drupal 10 Theme Development helps you explore the new Drupal 10’s theme layer in depth.

With a fully implemented Drupal website on the one hand and a set of Storybook components on the other, you’ll begin by learning to create a theme from scratch to match the desired final layout. Once you’ve set up a local environment, you’ll get familiarized with design systems and learn how to map them to the structures of a Drupal website. Next, you’ll bootstrap your new theme and optimize Drupal’s productivity using tools such as webpack, Tailwind CSS, and Browsersync. As you advance, you’ll delve into all the theme layers in a step-by-step way, starting from how Drupal builds an HTML page to where the template files are and how to add custom CSS and JavaScript. You’ll also discover how to leverage all the Drupal APIs to implement robust and maintainable themes without reinventing the wheel, but by following best practices and methodologies. Toward the end, you’ll find out how to build a fully decoupled website using json:api and Next.js.

By the end of this book, you’ll be able to confidently build custom Drupal themes to deliver state-of-the-art websites and keep ahead of the competition in the modern frontend world.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 388

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Modernizing Drupal 10 Theme Development

Build fast, responsive Drupal websites with custom theme design to deliver a rich user experience

Luca Lusso

BIRMINGHAM—MUMBAI

Modernizing Drupal 10 Theme Development

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Alok Dhuri

Publishing Product Manager: Uzma Sheerin

Senior Editor: Nisha Cleetus

Technical Editor: Jubit Pincy

Copy Editor: Safis Editing

Proofreader: Safis Editing

Indexer: Hemangini Bari

Production Designer: Alishon Mendonca

Business Development Executive: Puneet Kaur

DevRel Marketing Coordinators: Deepak Kumar and Mayank Singh

First published: August 2023

Production reference: 1100823

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul's Square

Birmingham

B3 1RB, UK.

ISBN 978-1-80323-809-8

www.packtpub.com

To my wonderful wife, Giulia, and my beautiful children, Greta and Gabriele, for their endless support and encouragement. Thanks for everything.

To all the members of the Drupal team at Sparkfabrik – in particular, Beppe, Cristina, Enrico, Luca, Matteo, Marco, Noemi, Roberto, and Valeria.

– Luca Lusso

Contributors

About the author

Luca Lusso is a Drupal developer with more than 15 years of experience; he started with Drupal 5 and PHP 5 in an era where deployments with File Transfer Protocol was still a thing. Since then, he worked as a consultant and contributed to building some of the biggest Drupal websites in Italy. Luca is also a teacher, and has taught Drupal to many different teams, from universities to big system integrators. Luca is an open source lover and Drupal contributor; he maintains popular modules such as WebProfiler and Monolog. He’s also a speaker at conferences such as DrupalCon Europe and Drupal Developer Days. Lately, he has shifted his interest to frontend performance. Luca holds a master’s degree in computer science, and he’s an Acquia-certified developer.

About the reviewers

Theodoros Ploumis is a 15-year Drupal full stack developer who loves programming, open source, and public speaking. He maintains several open source knowledge projects in the area of Drupal, DevOps, and tooling. As a full stack developer, he is always interested in learning new things and promoting best practices. Currently, he works for EWORX S.A., a 360-degree digital communication services company. 

Massimo Altafini, currently head of design at Nuvole.org, is a designer and has been a computer enthusiast since he was a teen, experiencing all the stages of the evolution of the web, from its origins to today. His 25+ years of professional life have focused mainly on UX design and frontend development, but he also has insights on backend development. He has been working with the Drupal CMS since 2006. He likes to think of himself as belonging to the “new” category of hybrid designer, a role that is able to combine knowledge related to communication design (including UX/UI/IA/A11y) with the needs and constraints of software development and CMS-based solutions.

Table of Contents

Preface

Part 1 – Styling Drupal

1

Setting up a Local Environment

Technical requirements

Git

Docker

DDEV

Visual Studio Code

Installing the demo site

Cloning and building

Composer

Configuration management

Drush

Default Content

Yarn

Exploring the demo site

Fields

Paragraph types

Content types

Vocabulary

Blocks

Views

Menus

Disabling production optimization

Summary

2

Setting a New Theme and Build Process

Where to start

Core

Contributed open source themes

Commercial

Custom

Using a starterkit

Keeping things updated

Clearing the cache

Which tools to use

Tailwind CSS

PostCSS

webpack

Browsersync

BackstopJS

Ensuring coding standards

Stylelint

ESLint

PHPCS

Setting up a build process

Summary

3

How Drupal Renders an HTML Page

What is a template?

WebProfiler

Twig

Custom modules

What is a render array?

The dump() function

Cache

Controllers and blocks

Regions

Controller actions

Blocks

How to inject CSS and JavaScript into a template

Libraries

Attaching the library to a render array

Custom CSS

Custom JavaScript

Alternate ways to render a controller action output

Summary

4

Mapping the Design to Drupal Components

What is a design system?

Design tokens

Atomic design

Storybook

Splitting mockups into components

The home page

The trips page

The Trip page

The level page

The Search page

The login page

The Contact Us page

Forecast page

Mapping components to Drupal structures

Menu

MenuItem

Block and Region

Social

MenuBlock

Footer

Picture and PictureWithCaption

Slide, Slider, Grid, and Card

Term and Details

Body

Map

Table

Trip

Quote

Weather and Forecast

Banner

Level

Search result

User Login

Summary

5

Styling the Header and the Footer

Regions and blocks

Passing PHP variables by reference

Retrieving the currently active theme

Rendering an array for (very) simple markup

Twig’s autoescape feature

How to override a template

Defining theme regions

Custom page.html.twig

Overriding custom templates

Including templates

Finding templates

Template suggestions

Providing a new suggestion

Blocks

Styling menus

Template preprocess

Xdebug

Summary

6

Styling the Content

Entity, fields, bundles, and display modes

Bundles

Display modes

Media and image styles

Image styles

Taxonomy terms

How to structure content

Using fields

Using paragraphs

Defining a new field formatter

Plugins

Customizing the WYSIWYG editor

Text formats

Alternative ways to manage content

Summary

7

Styling Forms

Understanding forms

Render elements

Theme wrappers

Process, pre-, and post-render

Altering existing forms

Styling forms

Styling generic forms

Styling specific form

Summary

8

Styling Views

View templates

Using a row plugin

Using fields

Exposed filters

Pagers

Summary

9

Styling Blocks

Technical requirements

Editorial blocks

Adding a new block suggestion

Injecting the block content into the template

Extracting field values from the entity

Extracting field values using a preprocess function

Extracting field values using a bundle class

Programmatic blocks

Titles and breadcrumbs

Title

Breadcrumb

Summary

10

Styling the Maintenance, Taxonomy, Search Results, and 403/404 Pages

Styling the maintenance page

Styling the taxonomy page

Styling taxonomy term fields

Styling the search results page

Extending Twig templates

Styling the error pages

Summary

Part 2 – Advanced Topics

11

Single Directory Components

Technical requirements

The new kid on the block

Why SDC?

How to create a component with SDC

Metadata

Twig

CSS

JavaScript

Using the component

Libraries

Slots

Overriding CSS and JavaScript

Overriding a component

Component metadata

Integration with Storybook

Conclusions

Summary

12

Creating Custom Twig Functions and Filters

Technical requirements

Creating a custom Twig function

Defining a Twig function for a render array

Using a custom Twig function

Useful core and contrib Twig functions

Creating a custom Twig filter

Useful core and contrib filters

Summary

13

Making a Theme Configurable

Technical requirements

Creating a theme settings form

Configuration management

Using theme settings in Twig and JavaScript

The Twig function

Using themes settings in JavaScript

Sub-theming

Overriding the logo

Overriding configurations

Overriding libraries

Overriding functions

Overriding regions

Summary

14

Improving Performance and Accessibility

Technical requirements

Performance

Google Lighthouse

Core Web Vitals

Converting images in WebP format

Responsive images

Lazy loading images

Critical CSS

Accessibility

ARIA attributes

Announcing changes

Accessible methods for hiding content

Keyboard navigation

Summary

Part 3 – Decoupled Architectures

15

Building a Decoupled Frontend

Technical requirements

Setting up the environment to build a decoupled site

RESTful Web Services

JSON:API

Differences between RESTful Web Services and JSON:API

Authenticated requests

Introduction to Next.js

Next.js

CORS

Next for Drupal

Summary

Index

Other Books You May Enjoy

Preface

Working with themes in Drupal is not an easy task, and it is typical to get lost digging through all the layers and APIs involved. Modernizing Drupal 10 Theme Development deep-dives into the theme layer of the new Drupal 10.

In this book, we’ll explore how the Content Management System builds its pages, starting with all the basic concepts you need to develop a new Drupal theme from scratch and progressing to new features, such as starter kits, Single Directory Components, and decoupled architectures.

We want you to concentrate on the book’s main topic, so we’ve provided a design system, the Drupal configuration, and an opinionated stack to run a website on your local machine.

Chapter after chapter, Modernizing Drupal 10 Theme Development will guide you from a set of unstyled pages to a production-ready website that is fast and accessible.

Of course, we’ll take a modern approach, using cutting-edge technologies, such as Storybook, theme starter kits, SDCs, and decoupled architectures.

I like to delve about a topic only after all the concepts it builds on are evident; for this reason, the order of some chapters may seem unusual. Trust me – this is better than going back and forth trying to remember in a later chapter what we discussed at the beginning of the book.

Who this book is for

This book has been designed with two kinds of developers in mind. The first are frontend designers, whose job is to take a configured Drupal site and provide a style, following some design guidelines. We expect those users to know HTML and CSS and be willing to get their hands dirty with some PHP code.

The second group consists of backend developers. Drupal provides many premade features and technologies that streamline the process of creating exceptional frontends. However, I often observe instances where developers redo things that Drupal already provides. With this book, my intention is for backend developers to embrace Drupal’s best practices as much as possible.

What this book covers

Chapter 1, Setting Up a Local Environment, guides you to set up an opinionated local environment to work with Drupal. You’ll learn how to install and configure some tools such as Docker, DDEV, and Visual Studio Code. We’ll then clone a Git repository, install Drupal, and set up the system to start working on the frontend.

Chapter 2, Creating a New Theme and Setting Up a Build Process, starts by discussing building a new theme instead of using a ready-to-use one. You’ll learn what a starter kit is and how to use it to generate a new theme. Finally, we set up some processes to enforce coding standards, both locally and in a continuous integration pipeline.

Chapter 3, How Drupal Renders an HTML Page, talks about the rendering pipeline of Drupal. You’ll learn everything you need to know about how Drupal turns its internal data structures into HTML pages, with CSS and JavaScript attached.

Chapter 4, Mapping the Design to Drupal Components, explains how to develop the design system. We’ll step away from Drupal briefly to talk about how to split pages into components and how to use tools such as Storybook to work on templates, before setting up a Drupal instance. Subsequently, we will map each component to a data structure in Drupal.

Chapter 5, Styling the Header and Footer, examines the layout that stays the same on every page. In this chapter, you’ll learn about regions and blocks, how to override a core template to provide your own, and how to style a Drupal menu.

Chapter 6, Styling the Content, digs into the main part of a Drupal page, the content. We’ll talk about entities and fields, media, and taxonomies. You’ll learn some different ways to structure content in Drupal and how to customize the WYSIWYG editor.

Chapter 7, Styling Forms, explores how forms work on a Drupal site. You’ll learn how a form is structured, which templates it uses, and how to override and style them. We’ll then use the acquired knowledge to style the user login form.

Chapter 8, Styling Views, discusses one of the most complex topics in Drupal core. The Views module is as powerful as it is difficult to understand and style. We’ll talk about Views templates, exposed filters, and pagers.

Chapter 9, Styling Blocks, details how to style the parts of a page that aren’t the main content. You’ll learn the differences between editorial and programmatic blocks and how to style titles and breadcrumbs.

Chapter 10, Styling Maintenance, Taxonomy, Search Results, and 403/404 Pages, discusses a set of pages that sometimes are overlooked but that provide a great level of professionalism if styled correctly.

Chapter 11, Single Directory Components, digs into one of the new features of Drupal. We’ll discuss how Drupal core implements the concept of components and how to leverage it to rebuild some of our templates using the new approach. You’ll learn how to use and override components and expose them to Storybook.

Chapter 12, Creating Custom Twig Functions and Filters, explains how to extend Twig. You’ll learn how to define a new function and a new filter for Twig and why this is the best way to move the business logic away from the theme layer.

Chapter 13, Making a Theme Configurable, explores how Drupal allows you to reuse the same theme on different websites by making it configurable. We’ll also talk about sub-theming and how and when it’s helpful to define a sub-theme.

Chapter 14, Improving Performance and Accessibility, discusses optimizations. You’ll learn how to improve the performance of your website and how to make it as accessible as possible, as your users deserve.

Chapter 15, Building a Decoupled Frontend, scratches the surface of one of the most hyped topics in recent years. We’ll talk about how to leverage Drupal APIs to expose content and configuration to third-party systems and how to write some simple JavaScript clients to consume that data. You’ll learn how to install and configure a Next.js instance to build a fully decoupled site.

To get the most out of this book

This book assumes you know HTML and CSS and some JavaScript. It also assumes that you can use basic shell commands, can install software from web downloads onto your computer, and have basic familiarity with an integrated development environment. Basic knowledge of PHP will also be helpful.

Software covered in the book

OS requirements

Docker

Windows, macOS, or Linux

DDEV

Windows, macOS, or Linux

GIT

Windows, macOS, or Linux

Visual Studio Code

Windows, macOS, or Linux

Drupal 10

Windows, macOS, or Linux

Next.js

Windows, macOS, or Linux

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Modernizing-Drupal-10-Theme-Development. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system.”

A block of code is set as follows:

<div class="relative">   <a href="{{ link }}" title="{{ title }}">     <div       class="z-10 h-48 w-full border-2 border-nord-4 bg-         cover bg-center bg-no-repeat opacity-50"       style="background-image:url('{{ image }}');"     ></div>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<div class="relative">   <a href="{{ link }}" title="{{ title }}">     <div       class="z-10 h-48 w-full border-2 border-nord-4 bg-         cover bg-center bg-no-repeat opacity-50"       style="background-image:url('{{ image }}');"     ></div>

Any command-line input or output is written as follows:

^ array:4 [   "uri" => "entity:node/8"   "title" => "Let's do some ice climbing"   "options" => []   "_attributes" => [] ]

Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Click on the Preferences link to open the Preferences window.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Modernizing Drupal 10 Theme Development, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781803238098

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1 – Styling Drupal

In this part, you will be introduced to the project we’ll work on for the entire book. We will start by setting up a local environment, deep-dive into how Drupal builds its page, and explore the design system we must implement.

After that, we will start styling each section of a demo website.

This part has the following chapters:

Chapter 1, Setting Up a Local EnvironmentChapter 2, Creating a New Theme and Setting Up a Build ProcessChapter 3, How Drupal Renders an HTML PageChapter 4, Mapping the Design to Drupal ComponentsChapter 5, Styling the Header and FooterChapter 6, Styling the ContentChapter 7, Styling FormsChapter 8, Styling ViewsChapter 9, Styling BlocksChapter 10, Styling Maintenance, Taxonomy, Search Results, and 403/404 Pages