古腾堡自定义块如何将数据从插件索引文件发送到js文件

时间:2019-11-22 12:58:24

标签: wordpress wordpress-gutenberg gutenberg-blocks create-guten-block

我已经在插件main / index php文件中注册了自定义块。

register_block_type('gutenberg-custom/show-information', array(
        'editor_script' => 'gutenberg-show-information',
        'style' => 'gutenberg-customblock-css',
    ));

我想将一些数据从此PHP文件发送到js文件,该文件包含该块的实际实现。原因是,我需要从PHP进行API调用,并在js代码的selectbox选项中使用该响应。请参阅下面的注释代码。这是js的代码。

edit: function(props) {
      console.log("props", props);
      return el(
        Fragment,
        {},
        el(
          InspectorControls,
          {},
          el(
            PanelBody,
            { title: "Show Settings", initialOpen: true },
            el(
              PanelRow,
              {},
              el(SelectControl, {
                label: "Select Exhibitor",
                options: [    // **these options are static I have given but I want these to be dynamic coming from the plugin main file or can be any PHP file 
                  { label: "Big", value: "100%" },
                  { label: "Medium", value: "50%" },
                  { label: "Small", value: "25%" }
                ],
                onChange: value => {
                  props.setAttributes({ exhibitor_id: value });
                },
                value: props.attributes.exhibitor_id
              })
            )
          )
        ),
        el(
          "div",
          {},
          "[show-information]"
        )
      );
    },

1 个答案:

答案 0 :(得分:0)

排队编辑器脚本时,可以“注入”传递给JS的变量:

wp_register_script('gutenberg-show-information', $pathToScript, [], null, true);
wp_localize_script(
  'gutenberg-show-information',
  YOURJSOBJECT,
  ['myVar' => 'foobarbaz'] <--- array of data you want to pass
);
wp_enqueue_script('gutenberg-show-information');

然后在您的javaScript文件中,您可以访问YOURJSOBJECT.myVar,它应该输出foobarbaz