简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM