Add summary to content

This commit is contained in:
Jake Howard 2022-06-26 19:52:20 +01:00
parent 299a6342cc
commit 2012b245a8
Signed by: jake
GPG key ID: 57AFB45680EDD477
3 changed files with 18 additions and 4 deletions

View file

@ -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] = []

View file

@ -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):

View file

@ -13,7 +13,7 @@
<div>
<h2 class="title is-3"><a href="{% pageurl page %}">{{ page.title }}</a></h2>
{% include "common/content-details.html" %}
{% lorem 1 p %}
<p>{{ page.summary }}</p>
</div>
</div>
</div>