function JsExampleController::showColors

JavaScript attachment demonstration.

We demonstrate how to attach a number of scripts to the render array via a library.

In this controller, on the Drupal side:

  • We create a container with an ID the scripts uses to identify the container.
  • We attach some scripts which generate color-coded content.
  • We add values to drupalSettings, which is used to pass data from PHP to JavaScript.

The order in which the color scripts are executed will end up being the order of the content.

Return value

array A render array.

1 string reference to 'JsExampleController::showColors'
js_example.routing.yml in modules/js_example/js_example.routing.yml
modules/js_example/js_example.routing.yml

File

modules/js_example/src/Controller/JsExampleController.php, line 45

Class

JsExampleController
Controller for JavaScript Example description page.

Namespace

Drupal\js_example\Controller

Code

public function showColors() {
  $colors = [
    'red' => $this->t('I am red.'),
    'blue' => $this->t('I am blue.'),
    'green' => $this->t('I am green.'),
    'cyan' => $this->t('I am cyan.'),
    'magenta' => $this->t('I am magenta.'),
    'yellow' => $this->t('I am yellow.'),
  ];
  $build['content'] = [
    '#markup' => '<div id="js-example-colors"></div>',
  ];
  // Attach the library.
  $build['#attached']['library'][] = 'js_example/colors';
  // Attach the JavaScript settings.
  $build['#attached']['drupalSettings']['javaScriptExample']['colors'] = $colors;
  return $build;
}