function drupal_merge_js_settings

Merges an array of settings arrays into a single settings array.

This function merges the items in the same way that


  jQuery.extend(true, {}, $settings_items[0], $settings_items[1], ...)

would. This means integer indices are preserved just like string indices are, rather than re-indexed as is common in PHP array merging.

Example:

function module1_page_build(&$page) {
  $page['#attached']['js'][] = array(
    'type' => 'setting',
    'data' => array(
      'foo' => array(
        'a',
        'b',
        'c',
      ),
    ),
  );
}
function module2_page_build(&$page) {
  $page['#attached']['js'][] = array(
    'type' => 'setting',
    'data' => array(
      'foo' => array(
        'd',
      ),
    ),
  );
}

// When the page is rendered after the above code, and the browser runs the
// resulting <SCRIPT> tags, the value of drupalSettings.foo is
// ['d', 'b', 'c'], not ['a', 'b', 'c', 'd'].

By following jQuery.extend() merge logic rather than common PHP array merge logic, the following are ensured:

  • drupal_add_js() is idempotent: calling it twice with the same parameters does not change the output sent to the browser.
  • If pieces of the page are rendered in separate PHP requests and the returned settings are merged by JavaScript, the resulting settings are the same as if rendered in one PHP request and merged by PHP.

Parameters

$settings_items: An array of settings arrays, as returned by:

$js = drupal_add_js();
$settings_items = $js['settings']['data'];

Return value

A merged $settings array, suitable for JSON encoding and returning to the browser.

See also

drupal_add_js()

drupal_pre_render_scripts()

5 calls to drupal_merge_js_settings()
AjaxResponse::ajaxRender in drupal/core/lib/Drupal/Core/Ajax/AjaxResponse.php
Prepares the AJAX commands for sending back to the client.
ajax_render in drupal/core/includes/ajax.inc
Renders a commands array into JSON.
drupal_pre_render_scripts in drupal/core/includes/common.inc
#pre_render callback to add the elements needed for JavaScript tags to be rendered.
file_ajax_upload in drupal/core/modules/file/file.module
Ajax callback: Processes file uploads and deletions.
WebTestBase::drupalPostAJAX in drupal/core/modules/simpletest/lib/Drupal/simpletest/WebTestBase.php
Execute an Ajax submission.

File

drupal/core/includes/common.inc, line 3161
Common functions that many Drupal modules will need to reference.

Code

function drupal_merge_js_settings($settings_items) {
  return NestedArray::mergeDeepArray($settings_items, TRUE);
}