Log1x / acf-composer

Compose ACF Fields, Blocks, Widgets, and Option Pages with ACF Builder on Sage 10.
https://github.com/Log1x/acf-composer
MIT License
413 stars 56 forks source link

feat(block): Add support for InnerBlocks templates #159

Closed Log1x closed 1 year ago

Log1x commented 1 year ago

This PR adds native support for the InnerBlocks template property making it easy + clean to add block templates to your ACF blocks.

A simple template adding a heading and paragraph would look something like:

public $template = [
    'core/heading' => ['placeholder' => 'Hello World'],
    'core/paragraph' => ['placeholder' => 'Welcome to the Example block.'],
];

I couldn't get block nesting as pretty as I wanted (e.g. when using core/column and core/columns) but it can be done using the innerBlocks attribute.

public $template = [
    'core/heading' => ['placeholder' => 'Hello World'],
    'core/columns' => [
        'innerBlocks' => [
            ['core/column' => [
                'innerBlocks' => [
                    ['core/heading' => ['level' => '3', 'placeholder' => 'This is a column heading.']],
                    ['core/paragraph' => ['placeholder' => 'This is a column paragraph.']],
                ],
            ]],
            ['core/column' => [
                'innerBlocks' => [
                    ['core/image' => []],
                ],
            ]],
        ],
    ],
];

After adding the $template property to your block class you would then pass $block->template to template in <InnerBlocks />.

<InnerBlocks template="{{ $block->template }}" />

Open to feedback/suggestions.

mike-sheppard commented 1 year ago

Perfect 👌

We currently do very similarly by passing through the with() method + we usually include allowed_blocks to restrict which blocks can be added (if relevant):

// app/Blocks/SomeBlock.php

public function with() {
  return [
      ...
      'allowed_blocks'    => $this->allowed_blocks(),
      'template'          => $this->block_template(),
  ];
}

public function block_template() {
  return esc_attr(wp_json_encode([
      ['core/heading', [
          'level'       => 2,
          'placeholder' => 'Your heading',
          'fontSize'    => 'sm',
      ]]
  ]));
}

public function allowed_blocks() {
    return esc_attr(wp_json_encode([
        'core/heading',
        'core/buttons',
    ]));
}
{{-- some-block.blade.php --}}

<InnerBlocks
  template="{!! $template !!}"
  allowedBlocks="{!! $allowed_blocks !!}"
/>