diff --git a/website/common/models.py b/website/common/models.py index a6deb52..c628b3c 100644 --- a/website/common/models.py +++ b/website/common/models.py @@ -9,7 +9,7 @@ from wagtail.fields import StreamField from wagtail.images import get_image_model_string from wagtail.models import Page -from .streamfield import get_blocks, get_word_count +from .streamfield import get_blocks, get_word_count, truncate_streamfield from .utils import TocEntry, get_table_of_contents @@ -63,6 +63,10 @@ class BaseContentMixin(models.Model): def word_count(self) -> int: return get_word_count(self.body) + @cached_property + def summary(self) -> str: + return truncate_streamfield(self.body, 50) + class ContentPage(BasePage, BaseContentMixin): # type: ignore[misc] subpage_types: list[Any] = [] diff --git a/website/common/streamfield.py b/website/common/streamfield.py index 0b91bc6..7b5e987 100644 --- a/website/common/streamfield.py +++ b/website/common/streamfield.py @@ -6,7 +6,7 @@ from django.utils.text import smart_split from wagtail import blocks from wagtail.embeds.blocks import EmbedBlock -IGNORE_WORDCOUNT_BLOCKS = (blocks.RawHTMLBlock, EmbedBlock) +IGNORE_PLAINTEXT_BLOCKS = (blocks.RawHTMLBlock, EmbedBlock) class LoremBlock(blocks.StructBlock): @@ -35,11 +35,21 @@ def get_blocks() -> list[tuple[str, blocks.BaseBlock]]: def get_plain_text(value: blocks.StreamValue) -> Iterator[str]: for block in value: - if isinstance(block.block_type, IGNORE_WORDCOUNT_BLOCKS): + if isinstance(block.block_type, IGNORE_PLAINTEXT_BLOCKS): continue yield strip_tags(str(block)) +def truncate_streamfield(value: blocks.StreamValue, words: int) -> str: + collected_words: list[str] = [] + for block_text in get_plain_text(value): + collected_words.extend(smart_split(block_text)) + if len(collected_words) >= words: + break + + return " ".join(collected_words[:words]) + + def get_word_count(value: blocks.StreamValue) -> int: count = 0 for chunk in get_plain_text(value): diff --git a/website/common/templates/common/listing-item.html b/website/common/templates/common/listing-item.html index b20ca3d..adc099c 100644 --- a/website/common/templates/common/listing-item.html +++ b/website/common/templates/common/listing-item.html @@ -13,7 +13,7 @@
{{ page.summary }}