Problem/Motivation
Using a custom block definition, I add drupalSettings for the front end as seen below. This no longer works. I have to add the drupalSettings via a hook_page_attachments() implementation so at least we have that as a workaround, but it's not optimal.
The block does appear on the page as expected. The javascript loads and the settings for the custom block in the Drupal javascript behavior are not present. Other custom settings added via hook_page_attachments are visible. I have locally created a simplified custom block test to reproduce and confirmed that adding attachments such as drupalSettings via a custom block build function no longer works.
<?php
namespace Drupal\my_custom_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\my_custom_module\MyCustomTools;
/**
* Provides a custom block.
*
* @Block(
* id = "my_custom_module_favorite_block",
* admin_label = @Translation("My Favorite Custom Block"),
* category = @Translation("Custom Blocks"),
* )
*/
class MyFavoriteCustomBlock extends BlockBase {
/**
* {@inheritDoc}
*/
public function build() {
$favorite_settings = MyCustomTools::getFavoriteSettings();
$build = [
'#theme' => 'my_custom_block',
'#favorite_settings' => $favorite_settings,
'#cache' => ['contexts' => ['url.path']],
];
// This isn't working. I have to use hook_page_attachments() to add the settings for the frontend.
$build['#attached']['drupalSettings']['my_custom_module']['mycustommodulefavoriteblock'] = $favorite_settings;
return $build;
}
}
!((document, Drupal) => {
'use strict';
/**
* JS for Favorite Custom Block
*/
Drupal.behaviors.favoriteCustomBlock = {
attach: function(context, settings) {
window.addEventListener('DOMContentLoaded', () => {
console.log('settings);
});
}
};
})(document, Drupal);
Steps to reproduce
Proposed resolution
Remaining tasks
User interface changes
Introduced terminology
API changes
Data model changes
Release notes snippet