[flask] jinja自定义filter来过滤html标签

问题描述

数据库存储了html格式的博客文章,在主页(index)显示的时候带有html标签,如何过滤掉呢?

解决方案

用jinja自定义filter过滤掉html标签

我是用的工厂函数,因此在工厂函数里面这样写

__init__.py
#省略。。。
def create_app():
    app = Flask(__name__)
    #省略。。。
    @app.template_filter('ellipsis')
    def do_ellipsis(arg):
        import re
        return re.sub(r"<.*?>",'',arg)
    #省略。。。
    return app
    
index.html
<p class="list-group-item-text blog-index-textbody">{{ post['body']|ellipsis  }}</p>

详见flask文档 - 模板

猜你喜欢

转载自www.cnblogs.com/remly/p/11801836.html