我想将 $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/