'Passing variable from render array in Controller to javascript in twig
I want to pass $reservationData to the twig template so I can use it in javascript.
Here is my Controller:
class MovieReservation extends ControllerBase{
public function page(){
return [
'#reservation' => $reservationData,
];
}
I need it in javascript functions so I can populate it with the informations I want.
How can I do that? Thanks in advance
Solution 1:[1]
You have to pass data into drupalSettings object :
class MovieReservation extends ControllerBase {
public function page() {
return [
'#reservation' => $reservationData, // It's for twig template.
'#attached' => [
'drupalSettings' => [
'reservation' => $reservationData, // It's for javascript file.
],
],
];
}
And into your javascript file:
drupalSettings.reservation
Note : You can add javascript file via libraries.yml file
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DarkteK |
