javascript - 将变量从 Controller 中的渲染数组传递到twig中的javascript

标签 javascript drupal twig drupal-8

我想将 $reservationData 传递给 twig 模板,以便我可以在 JavaScript 中使用它。

这是我的 Controller :

class MovieReservation extends ControllerBase{
  public function page(){
    return [
      '#reservation' => $reservationData,
    ];
  }

我在 JavaScript 函数中需要它,这样我就可以用我想要的信息填充它。

我怎样才能做到这一点?提前致谢

最佳答案

您必须将数据传递到 drupalSettings 对象中:

  class MovieReservation extends ControllerBase {
    public function page() {
      return [
        '#reservation' => $reservationData, // It's for twig template.
        '#attached' => [
           'drupalSettings' => [
             'reservation' => $reservationData, // It's for javascript file.
           ],
        ],
      ];
    }

并进入您的 javascript 文件:

drupalSettings.reservation

注意:您可以通过libraries.yml文件添加javascript文件

关于javascript - 将变量从 Controller 中的渲染数组传递到twig中的javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69724990/

相关文章:

javascript - 使用包含列表的 json 数据发送 post 请求

java - 将 EventSource(服务器发送的事件)连接到服务器时出错

javascript - Highcharts :Uncaught TypeError: $(. ..).highcharts 不是函数

javascript - 当 process.env.NODE_ENV= ='production' 时,使用 babel-polyfill 在 IE11.0.9600 中未定义 fetch 和 Headers

drupal - 使用 syslog 和 nginx/php-fpm

javascript - 如何使新选择的 html 选项成为首选?

Drupal View 使用关系时返回重复值

mysql - 在 Drupal 中过滤 theme_table

php - 显示大量带有类的表单行

performance - 与选民的 symfony 表演