By wim leers on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.0.x
Introduced in version:
8.0-BETA4
Issue links:
Description:
In order to optimize Drupal AJAX requests and the caching of CSS and JS aggregate files, JavaScript settings attached to Drupal render arrays were promoted to their own asset type.
- Before
-
$build = array( …, '#attached' => array( 'js' => array( array( 'type' => 'setting', 'data' => array('ckeditor' => array( 'hiddenCKEditorConfig' => $config, )), ), ), ), ), ); - After
-
$build = [ …, '#attached' => [ 'drupalSettings' => [ 'ckeditor' => ['hiddenCKEditorConfig' => $config], ] ], ];
hook_js_settings_build() has been added to allow modification of settings from library definitions, the results of this hook are cached.
An accompanying alter hook, hook_js_settings_alter() is also introduced. This means you no longer need to do crazy things in hook_js_alter().
- Before
-
/** * Implements hook_js_alter(). */ function user_js_alter(&$javascript) { // If >=1 JavaScript asset has declared a dependency on drupalSettings, the // 'settings' key will exist. Thus when that key does not exist, return early. if (!isset($javascript['settings'])) { return; } // Provide the user ID in drupalSettings to allow JavaScript code to customize // the experience for the end user, rather than the server side, which would // break the render cache. // Similarly, provide a permissions hash, so that permission-dependent data // can be reliably cached on the client side. $user = \Drupal::currentUser(); $javascript['settings']['data'][] = array( 'user' => array( 'uid' => $user->id(), 'permissionsHash' => \Drupal::service('user.permissions_hash')->generate($user), ), ); } - After
-
/** * Implements hook_js_settings_alter(). */ function user_js_settings_alter(&$settings) { // Provide the user ID in drupalSettings to allow JavaScript code to customize // the experience for the end user, rather than the server side, which would // break the render cache. // Similarly, provide a permissions hash, so that permission-dependent data // can be reliably cached on the client side. $user = \Drupal::currentUser(); $settings['user']['uid'] = $user->id(); $settings['user']['permissionsHash'] = \Drupal::service('user.permissions_hash')->generate($user); }
Impacts:
Module developers
Themers