Setting Template Defaults for Gutenberg InnerBlocks

While building a custom Gutenberg block that uses the InnerBlocks component, I realized that I wanted to limit the type of blocks that could be added and also set the default attributes for those blocks. For example, I wanted the “allowed blocks” for my InnerBlocks to include the image, heading and paragraph blocks, but for the heading block, I wanted the default level to be set to “H3” instead of “H2” and text alignment to be set to “center.” Below are steps for setting up these default attributes.

Steps:

I first set up the ALLOWED_BLOCKS constant with the array of blocks I wanted to allow:

const ALLOWED_BLOCKS = [ 'core/image', 'core/heading', 'core/paragraph' ];

Next, I set up the TEMPLATE constant with the array of blocks I wanted to be included with attributes and properties set up that would define the default settings for the added InnerBlocks.

const TEMPLATE = [
   [ 'core/heading', { placeholder: 'Card title (same as front side)', level: 3, textAlign: 'left' } ],
   [ 'core/paragraph', { placeholder: 'Back side content' } ]
];

Finally I added these properties to the InnerBlocks component in the edit function:

<InnerBlocks
      allowedBlocks={ ALLOWED_BLOCKS }
      template={ TEMPLATE }
      templateLock="false"
 />

Notes:

  • View the original source code for the above code examples.
  • The attributes for each block can be found in that block’s documentation. For example, I found all the attributes for the heading block in the heading block gutenberg documentation. With this information I was able to set the “level” and “textAlign” defaults for the heading block.

On line 31 there is a list of attributes for this block:

const { textAlign, content, level, placeholder } = attributes;

Issues:

A couple of issues I ran into might be due to the fact that the block I used these templates in is a child block.

  • I found that templateLock was not working the way I expected it to. For example, I wanted the user to be able to remove/add and rearrange blocks within that template.
  • I tried using the renderAppender property see if adding an “Add block” button would allow for at least the addition of more blocks to that InnerBlock, but this also didn’t work. The “Add” button didn’t even render.
  • I will update this section if I come up with a solution to any of these issues.

Resources:

  • Block Library containing all the core blocks where you can find attributes for different block types.

Comments

Comments for this post are closed.