简体   繁体   中英

How to create custom block in wagtail?

This is my StreamField :

body = StreamField([
    ('heading', blocks.CharBlock(classname="full title")),
    ('paragraph', blocks.RichTextBlock()),
    ('image', ImageChooserBlock()),
])

And my question is: how to add my own Block that I can pass to StreamField ? I meant block that contains multiple images, something like block? I didn't find answer for my question in wagtail docs.

When you asked:

I meant block that contains multiple images, something like block?

Here is an example of something you could try, I am not sure what specifically you are trying to achieve so I left it fairly generic but modify it how you like.

class GalleryBlock(blocks.StructBlock):
    """
    Nameable gallery with multiple images.
    """
    name = blocks.CharBlock(required=True)
    images = blocks.ListBlock(
        blocks.StructBlock([
            ("image", ImageChooserBlock(required=True)),
            ("alt_text", blocks.CharBlock(required=False, max_length=100)),
        ])
    )

Then you would, of course, need to add this into your StreamField for body .

Something like this maybe.

body = StreamField([
    ('heading', blocks.CharBlock(classname="full title")),
    ('paragraph', blocks.RichTextBlock()),
    ('image', ImageChooserBlock()),
    ('gallery', GalleryBlock(icon='image')), # add this line
])

Hope this helps you see how flexible and awesome these built-in blocks are and how awesome StreamField can be. Sometimes you need to combine them to build a specific structure for your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM