Search code examples
wordpresswordpress-gutenberg

createBlocksFromInnerBlocksTemplate with nested [core/group] elements


WordPress 5.6 has a new Block API. With "createBlocksFromInnerBlocksTemplate" we are able to create create blocks from InnerBlocks template.

I tried this function with the template underneath and it works without any problems.

const template = [
   [ 'core/paragraph', { content: 'Example block' } ],
   [ 'core/paragraph', { placeholder: __( 'Example content.' ) } ],
],

createBlocksFromInnerBlocksTemplate( template )

Now, i want to create a nested core/group that contains 2 columns. Each columns should have a core/heading and core/paragraph.

I started with this example underneath:

const template = [
   [ 'core/group', { layout: { type: "default" } ]
],

This creates a core/group as i want but how to go one with to columns and create for each columns again innerBlocks?

The result should look like:

<core/group>
  <core/columns>
      <core/column>
          <core/heading>
          <core/paragraph>
      </core/column>
  </core/columns>
  <core/columns>
      <core/column>
          <core/heading>
          <core/paragraph>
      </core/column>
  </core/columns>
</core/group>

Solution

  • The third parameter of the block template item array[] can contain the nested innerBlocks.

    const myTemplate = [ ["namespace/block", {..settings}, [ 'innerblocks'] ] ]
    

    The nesting can quickly become complex.

    /**
    * @see https://github.com/WordPress/gutenberg/blob/trunk/packages/block-editor/src/components/inner-blocks/README.md#template
    */
    const template = [
            [ 'core/columns', { level: 'level 1' }, [
                [ 'core/column', { level: 'level 2' }, [
                    [ "core/paragraph", { level: 'level 3' }, [ [ "...", {} ] ] ]
                ]
            ]
        ]
      ]
    ];
    

    gutenberg reference documentation