简体   繁体   English

将数据从模板发送到 gutenberg acf 块中的脚本

[英]Sending data from template to script in gutenberg acf block

I am registering custom block with ACF (acf_register_block_type) with a separate JavaScript file.我正在使用单独的 JavaScript 文件向 ACF (acf_register_block_type) 注册自定义块。 In the php template I have some ACF data.在 php 模板中,我有一些 ACF 数据。 Is it possible to send those data to the JavaScript?是否可以将这些数据发送到 JavaScript? There are multiple instance of the same block in one page and the ACF data is unique to each instance.同一块在一页中有多个实例,ACF 数据对于每个实例都是唯一的。 I am not sure how that works, because the JavaScript for block only loads once.我不确定它是如何工作的,因为块的 JavaScript 只加载一次。 I need some basic idea for this.我需要一些基本的想法。 The ACF data in the template file are quite a lot, so I could not just use data-attribute.模板文件中的ACF数据比较多,不能只用data-attribute。

acf_register_block_type(array(
    'name'              => 'testimonial',
    'title'             => __('Testimonial'),
    'description'       => __('A custom testimonial block.'),
    'render_template'   => get_template_directory() . '/template-parts/blocks/testimonial/testimonial.php',
    'enqueue_script'    => get_template_directory_uri() . '/template-parts/blocks/testimonial/testimonial.js',
));

I am using this above example.我正在使用上面的例子。 SO in this case, I am trying to send data from testimonial.php to testimonial.js所以在这种情况下,我试图将数据从 testimonial.php 发送到 testimonial.js

In WordPress, the PHP function localize_script() is used to pass data from PHP to JavaScript, which could work for your scenario, eg:在 WordPress 中,PHP function localize_script()用于将数据从 PHP 传递到 JavaScript,这可能适用于您的场景,例如:

<?php
function testimonial_enqueue_scripts()
{
    wp_enqueue_script('testimonial-script', get_template_directory_uri() . '/template-parts/blocks/testimonial/testimonial.js');
    wp_localize_script('testimonial-script', 'acf_vars', array(
        'data' => 'value to send to javascript'
    ));
}
add_action('wp_enqueue_scripts', 'testimonial_enqueue_scripts');
?>

In your JavaScript, the data can then be accessed as acf_vars.data在您的 JavaScript 中,数据可以作为acf_vars.data访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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