Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. Attribute.php

function Attribute::addClass

Adds classes or merges them on to array of existing CSS classes.

Parameters

string|array ...$args: CSS classes to add to the class attribute array.

Return value

$this

File

core/lib/Drupal/Core/Template/Attribute.php, line 182

Class

Attribute
Collects, sanitizes, and renders HTML attributes.

Namespace

Drupal\Core\Template

Code

public function addClass(...$args) {
    if ($args) {
        $classes = [];
        foreach ($args as $arg) {
            // Merge the values passed in from the classes array.
            // The argument is cast to an array to support comma separated single
            // values or one or more array arguments.
            $classes[] = (array) $arg;
        }
        $classes = array_merge(...$classes);
        // Merge if there are values, just add them otherwise.
        if (isset($this->storage['class']) && $this->storage['class'] instanceof AttributeArray) {
            // Merge the values passed in from the class value array.
            $classes = array_merge($this->storage['class']
                ->value(), $classes);
            $this->storage['class']
                ->exchangeArray($classes);
        }
        else {
            $this->offsetSet('class', $classes);
        }
    }
    return $this;
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal