10

In web design, a key design element is the container that may contain various other content and blocks and is styled in CSS.

Is there a Gutenberg container block that may contain other blocks? If so, I haven't found it yet.

It looks like the Gutenberg editor now supports representing nested blocks. Some folks have been requesting section blocks. Any love there yet?

I WAS able to change the Columns block to one column, but that feels like a clunky hack.

8 Answers 8

2

There's a new core "Section" block that will be available in an upcoming Gutenberg update which is intended to serve the role you're looking for I think:

Add Section block

6

I had a very hard time getting my first container/wrapper block ready for action. Here's what I've learned the last couple hours:

Because I had serious problems importing the InnerBlocks I decided to use the create-guten-block toolkit. After the installation I just had to execute npx create-guten-block. That provided me the structure of related files. Now I changed the file src/block/block.js to the following code:

import { registerBlockType } from '@wordpress/blocks';
import { InnerBlocks } from '@wordpress/editor';
const { __ } = wp.i18n;
registerBlockType( 'myplugin/container', {
    title: __( 'My Plugin Container', 'myplugin' ),
    icon: 'universal-access-alt',
    category: 'myplugin',
    getEditWrapperProps: function () {
        return {
            "data-align": "full"
        };
    },
    edit: function( props ) {
        return (
            <div className={ props.className }>
                <InnerBlocks />
            </div>
        );
    },
    save: function( props ) {
        return (
            <div>
                <InnerBlocks.Content />
            </div>
        );
    },
} );

After entering the directory via cli and running npm run build my plugin was ready and worked as expected.

The simple css I've used for this first step was for both, front and backend:

.wp-block-myplugin-container{
    padding-top: 50px;
    padding-bottom: 50px;
    background-color: purple;
}

I used this on a windows machine, after updating node to the newest version everything worked as expected. I'm happy with the result and focus on advanced settings (background color/image, margins, paddings,...) for this container now.

Happy coding!

1
4

This what the second phase of Gutenberg development will focus on. Devs can create a parent block with predefined innerblock to smooth the page setup process for users.

For now you can use InnerBlocks component.

import { registerBlockType } from '@wordpress/blocks';
import { InnerBlocks } from '@wordpress/editor';

const ALLOWED_BLOCKS = [ 'core/image', 'core/paragraph' ];
<InnerBlocks
    allowedBlocks={ ALLOWED_BLOCKS }
/>

registerBlockType( 'my-plugin/my-block', {
    // ...

    edit( { className } ) {
        return (
            <div className={ className }>
                <InnerBlocks />
            </div>
        );
    },

    save() {
        return (
            <div>
                <InnerBlocks.Content />
            </div>
        );
    }
} );

There's also templateLock and layouts options to manipulate the options. For more options see - Official Doc

8
  • Are the InnerBlock components already part of Gutenberg or do I have to register this?
    – Wes Modes
    Commented Oct 11, 2018 at 15:32
  • Yes, InnerBlock is already loaded with Gutenberg, all need to do is import it from wp-editor. Just like you import other components from wp-editor. Commented Oct 12, 2018 at 16:21
  • 1
    So I'm new to Gutenberg (but not WP nor web dev), and I don't know how to "import it from wp-editor" as you say. There is a lot of reference to importing blocks in various docs, but so far I haven't been able to figure out if it is a magic wp-editor option I haven't found yet, some menu option elsewhere, or whether I should be mucking about in PHP files. Would you mind pointing me to a resource for Gutenberg dummies?
    – Wes Modes
    Commented Oct 18, 2018 at 3:13
  • I'd recommend this tutorial - css-tricks.com/learning-gutenberg-1-series-intro . It explained JS(ES6), React and then Gutenberg Commented Oct 19, 2018 at 4:33
  • Appreciate you pointing me to resources, and while I am interested in understanding everything there is to know about creating Gutenberg blocks and Gutenberg‘s relationship to JavaScript, for now I just want to drive a nail that is sticking up, not handcraft a custom hammer. What is the simplest path to having a classable container block in my Gutenberg editor?
    – Wes Modes
    Commented Oct 23, 2018 at 15:44
3

Update October 2020 - WP 5.5.1 ships with the Group block which you can use as a container.

1

Here are two "container blocks" I used. First one is the Melonpan block container. It has many features... But if you just need a basic container block, here is the section block that does the work pretty well.

0

A few plugins have added wrapper/container blocks to Gutenberg. Editor Blocks is just one example.

0

I've created a custom-block like so:

const { registerBlockType } = wp.blocks;
const { InnerBlocks } = wp.blockEditor;
const { Dashicon, TextControl, CheckboxControl } = wp.components;

registerBlockType('gutenberg/custom-container', {
    title: 'Container',
    description: 'Control the max-width of a content or section',
    icon: 'slides',
    category: 'layout',

    attributes: {
        maxWidth: {
            type: 'number',
            default: 0
        },
        collapse: {
            type: 'boolean',
            default: false
        }
    },
    
    edit({attributes, setAttributes}) {
        const { maxWidth, collapse } = attributes;
        
        function setValue(value){ 
             const numberValue = parseInt(value);   
             setAttributes({ maxWidth: numberValue });
        }

        function checkCollapse(){                
            setAttributes({ collapse: !collapse });
        }

        return (
            <div className='custom-container'>
                <div className="components-placeholder__label standard-wrapper">
                    <Dashicon icon="slides" />
                    Container
                </div>
                <div className='flex-between align-center'>
                    <div>
                        <TextControl
                            className="default-label"
                            label="Width(px)" 
                            type="number" 
                            name="max-width"
                            value={maxWidth}
                            onChange={setValue}
                        />
                    </div>
                    <CheckboxControl
                        className="default-label"
                        heading="Collapse Padding"
                        checked={collapse}
                        onChange={checkCollapse}
                    />
                </div>
                <InnerBlocks />
            </div>
        );
    },
    save({attributes}) {
        const { maxWidth, collapse } = attributes;

        return (
            <div 
                className={!collapse ? 
                              'custom-container' : 
                              'custom-container space-none' 
                          }
                style={{ maxWidth: `${maxWidth}px`}}
            >
                <InnerBlocks.Content />
            </div>
        ); }
});

Hope it helps someone.

0

In WP 6.3 there's the native "group", but if you want to set something for it globally, you can't really override it or something.

Create a simple container class parent block


I've tested these codes exactly and you will have a container block in the end :-) (WordPress 6.3.1)
Codes are as simple as possible and there will be ALL parts you need.
If you just care about the JS part - see the end of this answer :-)

Note: JS is still required for this to work (no block.json option yet :( ), but you can use plain JS :-)

Ref docs: WP documentation for "Nested Blocks: Using InnerBlocks" - choose Plain

yourtheme/blocks/container/block.json

{
    "$schema": "https://schemas.wp.org/trunk/block.json",
    "apiVersion": 3,
    "name": "yourtheme/container",
    "title": "Container",
    "description": "Wrap elements",
    "style": [],
    "category": "text",
    "icon": "format-aside",
    "keywords": ["container"],
    "render": "file:./render.php"
}

yourtheme/blocks/container/render.php

<?php

/**
 * Your Container - block template
 *
 * @param WP_Block $block The block settings and attributes.
 */

declare(strict_types=1);

if (!defined('ABSPATH')) {
    exit();
}
?>
<div class="container">
    <?php
        /** @var WP_Block $block */
        echo $block->render(['dynamic' => false]);
    ?>
</div>
<?php

The JS part - yourtheme/functions.php

Ideally you want to save this to a separate JS file and do standard enqueuing, but this is the quick way out...

add_action('admin_head', function () {
    ?>
    <script>
    ( function ( blocks, element, blockEditor ) {
        const el = element.createElement;
        const InnerBlocks = blockEditor.InnerBlocks;
        const useBlockProps = blockEditor.useBlockProps;

        blocks.registerBlockType( 'yourtheme/container', {
            edit: function () {
                let blockProps = useBlockProps();
                // override all classes to just "container" (you can append if you want...)
                blockProps.className = 'container';

                return el( 'div', blockProps, el( InnerBlocks ) );
            },

            save: function () {
                let blockProps = useBlockProps.save();

                return el( InnerBlocks.Content );
            },
        } );
    } )( window.wp.blocks, window.wp.element, window.wp.blockEditor );
    </script>
    <?php
});
1
  • notes: 1. child template? => use get_stylesheet_directory() instead of get_template_directory_uri 2. in save in JS we are only saving the inner blocks - leaving the wrapper rendering all up to you (in render.php) 3. I also suggest adding some CSS clear at the end of the container in render.php and in the JS edit(render) or through admin CSS: .editor-styles-wrapper .is-root-container > .container:after { display: block; clear: both; content: ''; }
    – jave.web
    Commented Sep 10, 2023 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.