Basic Concepts of Single Directory Component in Drupal

29 / Dec / 2024 by Shubham Joshi 0 comments

What is a Component?

In web development, a component is a part of a web page or application that is modular and reusable, with a specific functionality or purpose. It’s like a building block that can be used to create complex interfaces.

Components are made up of HTML, CSS, and JavaScript code, and can be easily customized and reused across multiple pages or applications. Examples of components include navigation menus, forms, sliders, and buttons.

What is a Single Directory Component?

Single-Directory Components (often abbreviated as SDC) are Drupal core’s implementation of components. Within SDC, all files necessary to render the component are grouped together in a single directory (hence the name!). This includes Twig, YAML, and optional CSS, JavaScript, etc. SDC will automatically generate a library to load CSS/JS when the template is invoked.

Why Single Directory Component introduced in Drupal?

The SDC feature was introduced in Drupal 9 to address specific challenges and limitations in traditional theming and component-based development. Here are a few reasons:

1. Modern Development Paradigm

  • Trend Towards Component-Based Architecture: Modern frontend frameworks like React, Vue, and Angular organize UI elements as self-contained components. SDC brings this component-based development approach to Drupal, where all related files (Twig, CSS, JavaScript, and configuration) for a specific component are grouped in one directory.

2. Improve Code Organization

  • Traditional Approach Issues: Files for a single component are often scattered across multiple directories: Twig templates in /templates. CSS in /css or /scss. JavaScript in /js. This scattering makes it harder to manage, debug, and reuse components.
  • SDC Solution: By grouping everything into one directory, developers can focus on one self-contained folder for a specific feature or UI element.

3. Simplify Reusability

  • Traditional Challenge: Reusing components across themes or modules often requires duplicating templates, styles, and logic. Extending or overriding components could lead to inconsistencies.
  • SDC Solution: Components are self-contained and modular, making them easier to reuse or override in different themes or modules

4. Support for Design Systems

  • Traditional Challenge: Design systems require a structured approach to components. Scattered files make it harder to enforce consistency or adapt to modern workflows like using Storybook.
  • SDC Solution: SDC aligns Drupal with design systems by providing a structured and standardized approach to component creation. It facilitates integration with tools like Storybook for component libraries.

5. Alignment with Modern Standards

  • Keeping Drupal Competitive: With SDC, Drupal aligns with modern CMSs and frameworks that prioritize developer experience and modularity (e.g., WordPress block editor, React components). It modernizes the development experience, attracting developers familiar with component-based architectures.

6. Better Multilingual and Theming Support

    • Components within SDC can leverage Drupal’s translation and theming systems more effectively.
    • Translations are managed in Twig templates with t() functions.
    • Theme-specific components can override SDC without breaking core functionality.

Benefits of Using SDC

There are many benefits of using SDC

  • Organization: Grouping all necessary code into one directory makes finding and jumping between relevant files easier.
  • Automatic library creation: SDC will automatically look for my-component.css and my-component.js and add to an automatically generated library if found. You can specify additional assets and dependencies within the component’s YML file if necessary.
  • Reusability: Components are designed to be modular and reusable, which means that they can be easily integrated into multiple pages or applications.
  • Consistency: By using components, developers can ensure that their web pages or applications have a consistent look and feel throughout.
  • Scalability: Components can help make web pages or applications more scalable, as they can be easily added or removed as needed.
  • Testing: Components can often be tested in isolation, which can make it easier to identify and fix bugs or issues.
  • Collaboration: Using components can make it easier for teams of developers to work together, as they can share and reuse components across different projects.

How to work with SDC?

To develop SDC, things we need to know

  • If you’re using Drupal 9 you have to install the contrib module using this command composer requires ‘drupal/sdc:^1.0’.
  • For Drupal 10.1 and later core versions, the Single Directory Component (SDC) module is included in the core.
  • Enable the Single Directory Components module.
  • In Drupal 10.3 Single-Directory Components became part of the render system.
  • Disable CSS and JS aggregation in the Drupal admin UI for development purposes.
  • Enable Twig development mode and disable caching.

Create A Component

  1. Create a new directory called components/ in your custom theme or module’s directory.
  2. Create a new directory within the components/ directory with the name of your new component (ex – carousel).
  3. Create two new files within this directory
    1. A twig file with the name of your component (ex carousel.twig)
    2. A YAML file with the *.component.yml extension that is named with your component (ex carousel.component.yml).
  4. The CSS and JavaScript must be named after the component (e.g., carousel.css, and carousel.js) to load them automatically.
  5. You can load additional styles, scripts, and dependencies using the libraryOverrides key within your

Final directory structure

As an example, we are creating a component in a custom module.

|- web/modules/custom/my-module
    |- components
        |- my-component
            |- my-component.twig (required)
            |- my-component.component.yml (required)
            |- README.md (optional)
            |- thumbnail.png  (optional)
            |- my-component.js
            |- my-component.css
            |- assets (optional)
                |- img1.png

Drush Command with SDC

drush generate single_directory_component

Note – Minimum drush version – Drush 12 or later

Some Common Terminology before diving into *.component.yml file

Within the Drupal Single Directory Component (SDC) framework, data can be transmitted to a component using two methods: “props” (short for “properties”) and “slots.” These concepts originate from JavaScript frameworks like Vue and React, embodying the notion of providing or feeding data into a component.

  • Props adhere to a specified structure for transmitting data to the component, utilizing the JavaScript Object Notation (JSON) format with key-value pairs.
  • Slots handle unstructured data, encompassing scenarios like nested components, Twig blocks, or HTML markup. Unlike props, slots do not require a JSON schema with key-value pairs and are not confined by JSON data types.

Exploring component.yml File – Metadata

The presence of the *.component.yml file is important; in its absence, Drupal remains uninformed about the existence of your component. This file must be created within the component’s directory. Let’s go through the definition of *.component.yml file.

KEY DEFINITION
name Name of the component.
description Detailed explanation of the component.
schema props Are the properties like mail, image, headline, etc?
schema slots A container to put data that does not have a template or data structure.
libraryOverrides To add extra JS or css libraries apart from libraries that are inside the component’s directory.

Example of Component YAML file

Here, we are creating a carousel component in a custom module having props as a title and slider.

On the below path web/modules/custom/my-module/components/carousel.component.yml

# This is so your IDE knows about the syntax for fixes and autocomplete.
$schema: 'https://git.drupalcode.org/project/drupal/-/raw/10.1.x/core/modules/sdc/src/metadata.schema.json'

# The human readable name.
name: Carousel

# Status can be: "experimental", "stable", "deprecated", "obsolete".
status: stable

props:
  type: object
  properties:
    title:
      type: string
      title: Section Title
      description: The title shown above the carousel (e.g. "popular courses")
    slides:
      type: array
      title: Carousel Slides
      items:
        type: object
        properties:
          image:
            type: object
            required:
              - url
              - alt
            properties:
              url:
                type: string
                title: Image URL
              alt:
                type: string
                title: Image Alt Text
          title:
            type: string
            title: Slide Title
          description:
            type: string
            title: Slide Description
  required:
    - title
    - slides


Render a Component

To use a component in an *.html.twig template uses Twig’s built-in embed or include functions.

  • Use include(): Use the Twig include() function if there are no slots or arbitrary HTML properties and the data all follows a defined structure. Example –
    {{ include('my-module:carousel',{ props:{
        title: 'Carousel',
        slides: [
          {
            image: {
              url: 'https://images.unsplash.com/photo-1508766206392-8bd5cf550d1c',
              alt: 'Internal medicine course image'
            },
            title: 'internal medicine i',
            description: 'Explore the intricacies of diagnosing and treating adult diseases! From common ailments to complex medical conditions, gain a comprehensive understanding of internal medicine.'
          }
        ]
      }}) }}
    
  • Use {% embed %}: Use a Twig {% embed %} tag if you need to populate slots.
    Example of embed function.
    Here data will be the dynamic object of the slider and the slider title will be passed as a slot

    {% embed 'my-module:carousel' with { props:{
        slides: data
      }}
    %}
      {% block heading %}
        {{ slider_title }}
      {% endblock %}
    {% endembed %}

Override a Component

Only themes can override components, and there are two important requirements to do so:

  1. Add a replaces key at the top in the *.component.yml file you want to override
    name: Override existing Carousel
    replaces: my-custom.carousel
    
  2. The component needs to have a defined schema.

It is important to note that modules cannot override components, and only components that have a defined schema can replace and be replaced by others.

Conclusion

This blog will help you create a Basic Single Directory Component in your Drupal application. SDC lets you define schemas in the YML file, enabling contributed modules and Drupal core to automatically generate forms for data entry. This allows us to add components directly using tools like Layout Builder and CKEditor without needing custom entities.

FOUND THIS USEFUL? SHARE IT

Tag -

Drupal

Leave a Reply

Your email address will not be published. Required fields are marked *