This code sample is being provided as part of Debug Academy's "Intermediate Drupal Front End Development" talk from DrupalCon Portland 2024.
The talk was presented at DrupalCon by Nagat Ahmed and Ashraf Abed. This free code sample is being provided by the Drupal training company, Debug Academy. Learn more about our Drupal courses to accelerate your career.
- Become a Drupal developer (part-time, 3 month course)
- Drupal Architect Series
- Advanced module development
- Acquia Front End Certification Prep
- All Drupal training courses
This code sample includes the following files & folders:
- README.md
- yourtheme/yourtheme.info.yml
- yourtheme/yourtheme.libraries.yml (and uswds/)
- yourtheme/components/accordion/
- yourtheme/templates/node--faq.html.twig
Explanations follow:
This is the file you're reading right now. I hope I'm helpful!
A subset of a theme's .info.yml file.
Included to demonstrate adding the Single Directory Components (sdc) module as a dependency to your theme. This is because the code sample relies on the sdc
module.
Click here to access the file.
The USWDS CSS & JS files are located at:
- uswds/uswds.min.css
- uswds/uswds.min.js
They were downloaded from the USWDS website and saved into yourtheme/uswds/
The yourtheme.libraries.yml file 'registers' the USWDS CSS & JS files as yourtheme/uswds
.
This makes it possible for Drupal to automatically load them whenever your component is displayed.
- Click here to access the libraries.yml file.
- Click here to access the USWDS folder.
This folder contains two files:
- accordion.component.yml
- accordion.twig
The accordion.component.yml
file 'registers' our component in Drupal. Essentially, this makes Drupal aware of the accordion component's existence.
It also lists the yourtheme/uswds
library as a dependency. This way the USWDS CSS & JS automatically load whenever this component displays.
The accordion.twig
file contains the TWIG (dynamic markup) for our component. This, along with any dependencies (e.g. CSS/JS), is what loads when we display our component.
P.S. Single directory components would also automatically load accordion.css and accordion.js, if we had created those files within our components/accordion/ folder.
Click here to access the components/accordion folder.
In this file, we replace the default output for the site's FAQ content type with our accordion "single directory component".
We render all of the required variables (more information in the file's comments) to ensure we don't break any functionality provided by Drupal.
Click here to access the node--faq file.