JSON File in Gutenberg

时间:2019-02-12 作者:180690

嗨,我想用一个新的Kategorie创建一个块。如果我选择了新的块类型,它应该会显示一个包含由JSON文件生成的选项的select字段。JSON代码如下所示。这可能吗?

{
    "name": {
        "text": "Name",
        "value": "[value]",
        "content": "0"
    }
}
我读过类似服务器端渲染的内容。

1 个回复
SO网友:HU ist Sebastian

您可以使用好的ol“wp\\u localize\\u脚本来完成这一点。

步骤1:注册blocks脚本时,您已经可以执行以下操作:

wp_register_script(
      \'my-awesome-block\',
      plugins_url(\'/blocks/dist/blocks.build.js\', __FILE__),
      array(\'wp-blocks\', \'wp-element\',\'wp-editor\',\'wp-components\',\'lodash\'),
      filemtime(plugin_dir_path(__FILE__).\'blocks/dist/blocks.build.js\')
    );
在此之后(在同一函数内)插入:

//Do whatever to parse the json-file or get the categories, get them into a nice array like $my_awesome_json_kats. I would recommend to build an array like this for use with the select control:
//array(
//    array(
//      \'label\' => \'My First Option\',
//      \'value\' => \'my_first_option\'
//    ),
//    array(
//      \'label\' => \'My Second Option\',
//      \'value\' => \'my_second_option\'
//    ), 
//)
wp_localize_script(\'my-awesome-block\',\'blockcats\',array(\'jsoncats\' => $my_awesome_json_kats);
步骤2:在块脚本中,您现在可以访问名为blockcats的全局变量,它是您本地化的所有内容的对象

var my_kats = blockcats.jsoncats;
//now you can build your Select Control
const MySelectControl = withState( {
    size: \'50%\',
} )( ( { size, setState } ) => ( 
    <SelectControl
        label="My Awesome JSON Cats"
        value={ size }
        options=my_kats
        onChange={ ( size ) => { setState( { size } ) } }
    />
) );
//Took this code from the Docs for SelectControl, maybe you have to use it somehow else, but the options should be set to my_kats
第三步:???

第四步:利润!;)

快乐的编码!

相关推荐