diff --git a/wagtail/create_custom_nested_block_for_streamfield.md b/wagtail/create_custom_nested_block_for_streamfield.md new file mode 100644 index 0000000..e3f0578 --- /dev/null +++ b/wagtail/create_custom_nested_block_for_streamfield.md @@ -0,0 +1,87 @@ +# Create a Custom Nested Block for Wagtail StreamField + +- allows for more complex data structures within a `StreamField` +- common use case for a custom nested block is a "Card" layout, where each card contains an image, a title, a short text, and an optional link +- Featured products, team members, etc. + +## Define blocks + +```python +from wagtail.core import blocks +from wagtail.images.blocks import ImageChooserBlock + +# Individual blocks to be nested +class TitleBlock(blocks.CharBlock): + class Meta: + template = "blocks/title_block.html" + +class TextBlock(blocks.TextBlock): + class Meta: + template = "blocks/text_block.html" + +# Main nested block +class CardBlock(blocks.StructBlock): + image = ImageChooserBlock(required=True) + title = TitleBlock(required=True, max_length=100) + text = TextBlock(required=True, max_length=400) + link = blocks.URLBlock(required=False) + + class Meta: + template = "blocks/card_block.html" + icon = "placeholder" +``` + +## Create Templates for Your Blocks + +For each custom block, especially the `CardBlock`, you need to create a corresponding template that defines how the block should be rendered. Place these templates in your templates directory, under a `blocks` folder for organization. + +**Title Block Template (`title_block.html`):** + +```html +
{{ value }}
+``` + +**Card Block Template (`card_block.html`):** + +```html +