You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Controller中render数组的变量传递到Twig模板的JavaScript中使用

实现方法

1. 完善控制器渲染配置

先给返回的渲染数组指定关联模板,同时附加后续要用的JS资源:

class MovieReservation extends ControllerBase{
  public function page(){
    return [
      // 自定义模板标识,和后续hook_theme注册的对应
      '#theme' => 'movie_reservation_page',
      // 传递的预约数据
      '#reservation' => $reservationData,
      // 附加自定义JS库
      '#attached' => [
        'library' => '你的模块名/movie_reservation_script',
      ],
    ];
  }
}

把代码里的你的模块名替换为你实际的模块机器名。

2. 注册Twig模板

在模块根目录的你的模块名.module文件中添加钩子注册模板:

/**
 * Implements hook_theme().
 */
function 你的模块名_theme($existing, $type, $theme, $path) {
  return [
    'movie_reservation_page' => [
      'variables' => [
        'reservation' => NULL,
      ],
      // 对应模板文件名为 movie-reservation-page.html.twig
      'template' => 'movie-reservation-page',
    ],
  ];
}

在模块的templates目录下新建movie-reservation-page.html.twig文件作为自定义模板。

3. 模板内传递变量到JS上下文

在movie-reservation-page.html.twig中写入以下内容,将PHP变量转为JS可读取的格式:

{{ attach_library('core/drupalSettings') }}
{# 将预约数据存入Drupal全局配置对象 #}
{% set jsSettings = {
  reservationData: reservation
} %}
{{ jsSettings|drupal_attach_settings }}

{# 页面其他HTML内容写在下方 #}
<div class="reservation-page-container">
  <!-- 页面结构 -->
</div>

如果你不希望用drupalSettings,也可以用JSON标签的方式传递:

{% if reservation is not empty %}
<script type="application/json" id="reservation-data">
  {{ reservation|json_encode|raw }}
</script>
{% endif %}

4. 注册JS库

在模块根目录的你的模块名.libraries.yml中添加JS库配置:

movie_reservation_script:
  js:
    # 你的JS文件路径,放在模块的js目录下
    js/movie-reservation.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

5. JS中读取变量

在你自定义的js/movie-reservation.js文件中读取变量即可使用:

(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.movieReservation = {
    attach: function (context, settings) {
      // 方式1:从drupalSettings读取变量
      const reservationData = settings.reservationData;

      // 方式2:如果用JSON标签传递,用这个方式读取
      // const reservationData = JSON.parse(document.getElementById('reservation-data').textContent);
      
      // 你的业务逻辑直接使用reservationData即可
      console.log(reservationData);
    }
  };
})(jQuery, Drupal, drupalSettings);

所有配置完成后清空Drupal缓存即可生效。

内容的提问来源于stack exchange,提问作者MajaB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:36:06