Block grammar basics


First step: Block basics.

If you have already built your own blocks, block variations or block styles,
you may want to skip this part.

I am not going to talk about building blocks with JavaScript,
rather about the HTML code, or the so called block grammar
that we will be using in block based themes.

A basic block uses an HTML comment,
that is then parsed and rendered as HTML on the front.

<!-- /-->

The comment can be single line, and self closing,
or it can be a wrapper for actual HTML content.

Let’s look at these two examples:
The search block and the paragraph block.

<!-- wp:search /--> <!-- wp:paragraph --> <p>Welcome to the world of blocks.</p> <!-- /wp:paragraph -->

We know that the search block outputs a form on the front.

But the comment is self closing, because it doesn’t have any content.

The paragraph block prints our text content, and the comment is used as a wrapper.

It tells us where the paragraph starts, and where it ends.

Our third example, the group block,
has a comment wrapper and inner blocks based on divs.

<!-- wp:group --> <div class="wp-block-group"> <div class="wp-block-group__inner-container"> </div> </div> <!-- /wp:group -->

Most blocks can also have extra attributes.

When we make changes to a block in the editor,
for example to add a color, this is stored as a JSON object inside the block comment.

Our updated group block now has a background color.

<!-- wp:group {"style":{"color":{"background":"#1eadea"}}} --> <div class="wp-block-group has-background" style="background-color:#1eadea"> <div class="wp-block-group__inner-container"></div></div> <!-- /wp:group -->

This information is added both in the comment, and as an inline style on the div.

If we had chosen a predefined color, a class name would be used instead of the inline style.

<!-- wp:group {"backgroundColor":"vivid-purple"} --> <div class="wp-block-group has-vivid-purple-background-color has-background"> <div class="wp-block-group__inner-container"></div></div> <!-- /wp:group -->

This duplication is important to remember when we start manipulating blocks in our HTML files.