admin管理员组

文章数量:1134572

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.

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.

Share Improve this question asked Oct 4, 2018 at 23:35 Wes ModesWes Modes 2051 gold badge2 silver badges9 bronze badges
Add a comment  | 

8 Answers 8

Reset to default 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

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!

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

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

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.

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

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.

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
});

本文标签: cssAre there Gutenberg container blocks