wordpress - Gutenberg 自定义块如何将数据从插件索引文件发送到 js 文件
问题描述
我已经在插件主/索引 php 文件中注册了自定义块。
register_block_type('gutenberg-custom/show-information', array(
'editor_script' => 'gutenberg-show-information',
'style' => 'gutenberg-customblock-css',
));
我想将此 PHP 文件中的一些数据发送到包含该块的实际实现的 js 文件。原因是,我需要从 PHP 进行 API 调用,并在 js 代码的选择框选项中使用该响应。请参阅下面的注释代码。这是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]"
)
);
},
解决方案
当您将编辑器脚本排入队列时,您可以“注入”传递给 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
推荐阅读
- arrays - 使用readarray时如何避免数组元素后的换行符?
- c# - '不存在数据时尝试读取无效。'
- python - 在参数中设置一个列表以从 python 调用 API
- apache-spark - 如何将每个 user_id 第一行的列中的值复制到相同 user_id 的第二行
- python-3.x - 通过 REST 框架在 Django 模型中进行健壮搜索的正确方法
- assembly - 如何找到编译器优化的内容?
- python - 根据条件从数据框中获取一列到另一个
- laravel - 用户的 Laravel 帖子在一列中,按行分隔,用户名在同一列的第一行
- python - 使用 TensorFlow 模型评估输入的简单方法?
- javascript - 将 Array<[string, number]> 字符串排序为日期