使用 Jinja 过滤器创建内容片段 [英] Create content snippet with Jinja filter

查看:26
本文介绍了使用 Jinja 过滤器创建内容片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的主页创建内容片段.一个示例帖子看起来像

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>

在主页上,我只希望显示 之前的内容.我在想我可以在 Jinja 过滤器中使用 Beautiful Soup 来删除 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.

我该怎么做?

推荐答案

没有必要使用 Beautiful Soup.只需检查文本中是否存在 <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 = '
'

    return Markup(value.split(sep, 1)[0])

这篇关于使用 Jinja 过滤器创建内容片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆