function JsExampleController::showColors
Weight 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 use the 'weight' attribute to set the order in which the scripts are included in the library declaration.
- 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.
The 'weight' attribute in the .libraries.yml file determines the order in which a script is added to the page. To see this in action:
- Uncheck the "Aggregate Javascript files" setting on admin/config/development/performance.
- Visit examples/js_example/colors and examine the page source. You will see that the color scripts have been added to <head> following the weight order.
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 55
Class
- JsExampleController
- Controller for JavaScript Example description page.
Namespace
Drupal\js_example\ControllerCode
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.'),
];
// We give use an ID so that to target the HTML markup we added.
$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;
}