使用 Jinja 过滤器创建内容片段
Create content snippet with Jinja filter
我想为我的主页创建内容片段。一个例子 post 看起来像
<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>
主页上我只想显示<readmore/>
之前的东西。我在想我可以在 Jinja 过滤器中使用 Beautiful Soup 来删除 readmore 及其之后的所有内容。如果不存在 <readmore/>
,它应该在第一个换行符或段落末尾剪辑。
我该怎么做?
不用Beautiful Soup。只需检查文本中是否存在 <readmore/>
或其他一些子字符串,并在其上拆分,或者如果它不存在,则在换行符上拆分。
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])
我想为我的主页创建内容片段。一个例子 post 看起来像
<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>
主页上我只想显示<readmore/>
之前的东西。我在想我可以在 Jinja 过滤器中使用 Beautiful Soup 来删除 readmore 及其之后的所有内容。如果不存在 <readmore/>
,它应该在第一个换行符或段落末尾剪辑。
我该怎么做?
不用Beautiful Soup。只需检查文本中是否存在 <readmore/>
或其他一些子字符串,并在其上拆分,或者如果它不存在,则在换行符上拆分。
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])