用Jinja过滤器创建内容片段 [英] Create content snippet with Jinja filter
问题描述
我想为我的主页创建内容片段。一个示例文章看起来像
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>
在主页上我只想要< readmore /> ;
显示出来。我想我可以使用Jinja过滤器中的美丽的汤来切出更多的内容和所有的内容。如果没有< readmore />
存在,它应该在第一个换行符或段落结束时剪辑。
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.
我可以做这个吗?
推荐答案
没有必要使用美丽的汤。只要检查< readmore />
或其他一些子字符串是否存在于文本中,并在它上面进行分割,或者是否在新行上进行分割。
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])
这篇关于用Jinja过滤器创建内容片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!