3

I want to create content snippets for my home page. An example post looks something like

<p>Your favorite Harry Potter characters enter the Game of Thrones 
universe, and you'll never guess what happens!</p>

<readmore/>

<p>...they all die</p>

On the home page I only want the things before <readmore/> to show up. I'm thinking the I can use Beautiful Soup in a Jinja filter to cut out the readmore and all the content after it. It should clip at the first newline or paragraph end if no <readmore/> is present.

How can I do this?

davidism
  • 121,510
  • 29
  • 395
  • 339
kai
  • 1,288
  • 3
  • 12
  • 24

1 Answers1

4

There's no need to use Beautiful Soup. Just check if <readmore/> or some other substring is present in the text, and split on it, or if it's not there split on newline.

from markupsafe import Markup

@app.template_filter()
def snippet(value):
    for sep in ('<readmore/>', '<br/>', '<br>', '</p>'):
        if sep in value:
            break
    else:
        sep = '\n'

    return Markup(value.split(sep, 1)[0])
davidism
  • 121,510
  • 29
  • 395
  • 339