[Answered ]-Display Word Count in Blog Post with Wagtail

2👍

A template tag wouldn’t be the best approach here – templates are concerned with the presentation of the page, but the word count is a meaningful property of the page data that’s independent of any particular presentation. I’d suggest defining word_count as a method on your page model instead – then it’s always available as page.word_count(), or {{ page.word_count }} in templates. Here’s an example of how it could work (using the str.split method, which splits on spaces, as a cheap-and-cheerful way of getting a word count):

class BlogPage(Page):
    intro = RichTextField()
    body = StreamField([
        ('heading', blocks.CharBlock()),
        ('paragraph', blocks.RichTextBlock()),
        ('image', ImageChooserBlock()),
    ])

    def word_count(self):
        count = len(self.intro.split())
        for block in self.body:
            if block.block_type == 'paragraph':
                count += len(str(block.value).split())

        return count
👤gasman

Leave a comment