11.Wagtail streams應用-2

學航發表於2020-12-27

建立標準塊

修改blocks模型,建立CardsBlock模型

from wagtail.core import blocks
from wagtail.images.blocks import ImageChooserBlock


class TitleBlock(blocks.StructBlock):
    text = blocks.CharBlock(
        required=True,
        help_text="要顯示的文字",
        verbose_name="文字"
    )

    class Meta:
        template = "streams/title_block.html"
        icon = "edit"
        label = "標題"
        help_text = "居中顯示在頁面上的文字"


class CardsBlock(blocks.StructBlock):
    cards = blocks.ListBlock(
        blocks.StructBlock(
            [
                ("title", blocks.CharBlock(max_length=100, help_text="幫助文字", verbose_name="標題")),
                ("text", blocks.TextBlock(max_length=255, help_text="幫助文字", required=False, verbose_name="文字")),
                ("image", ImageChooserBlock(help_text="幫助文字"))
            ]
        )
    )

    class Meta:
        template = "streams/cards_block.html"
        icon = "image"
        label = "標準卡"

homo應用新增模型

from django.db import models
from wagtail.admin.edit_handlers import FieldPanel, PageChooserPanel, StreamFieldPanel
from wagtail.core.fields import StreamField
from wagtail.core.models import Page
from wagtail.images.edit_handlers import ImageChooserPanel
from streams import blocks


class HomePage(Page):
    lead_text = models.CharField(
        max_length=140,
        blank=True,
        help_text="橫幅標題下副文字",
        verbose_name="引導文字")
    button = models.ForeignKey(
        "wagtailcore.Page",
        blank=True, null=True,
        related_name="+",
        help_text="選擇要連線的頁面",
        on_delete=models.SET_NULL,
        verbose_name="按鈕")
    button_text = models.CharField(
        max_length=50,
        default="閱讀更多",
        blank=False,
        help_text="按鈕文字",
        verbose_name="按鈕文字")
    banner_background_image = models.ForeignKey(
        "wagtailimages.Image",
        blank=False,
        null=True,
        related_name="+",
        help_text="橫幅背景影像",
        on_delete=models.SET_NULL)
    body = StreamField([
        ("title", blocks.TitleBlock()),
        ("cards", blocks.CardsBlock()),
    ], null=True, blank=True, verbose_name="文字")
    content_panels = Page.content_panels + [
        FieldPanel("lead_text"),
        PageChooserPanel("button"),
        FieldPanel("button_text"),
        ImageChooserPanel("banner_background_image"),
        StreamFieldPanel("body")
    ]

cards_block.html

{% load wagtailimages_tags %}

{% for card in self.cards %}
  {% image card.image fill-570x370 as img%}
  <img src="{{ img.url }}" alt="{{ img.alt }}">
  <h3>{{ card.title }}</h3>
  {% if card.text %}
    <p>{{ card.text }}</p>
  {% endif %}
{% endfor  %}

在這裡插入圖片描述
在這裡插入圖片描述

相關文章