Access block styles before block is rendered

In our Gutenberg blocks we can access the $block variable to do something with the block styles $block->classes .

We implemented the styles, so blocks can be set to light or dark. This code is present in all our components, so we want to make this more modular. We tried to add this code in section.php (see below), but unlike in the block itself the $block variable is not accessible there. Does anybody know if we can retrieve the block styles there?

namespace App\View\Composers;

use Roots\Acorn\View\Composer;

class Sections extends Composer
{
    /**
     * List of views served by this composer.
     *
     * @var array
     */
    protected static $views = [
        'blocks.*',
    ];

    /**
     * Data to be passed to view before rendering.
     *
     * @return array
     */
    public function with()
    {        
        return [
            'nightTheme' => str_contains($block->classes, 'is-style-dark') ? 'night night:bg-gray-900 apply-py' : '',
        ];
    }
}

You can get the block classes etc. from your block.

In your with() method:

dd($this);

and

dd($this->block);
1 Like

Thanks Tombro, that works, I used $this->data->block->classes to retrieve the classes!

1 Like