怎么在flask框架中自定义过滤器

2023-06-13

这篇文章将为大家详细讲解有关怎么在flask框架中自定义过滤器,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一. 自定义一个mardown过滤器

自定义一个markdown过滤器, 使过滤器可以像safe解析html标签一样解析md语法.

  • 安装库

pip install Markdown==2.3.1
  • 自定义过滤器

使用@app.template_filter(‘md')过滤器, 此时便拥有了名为md的过滤器.

@app.template_filter('md')
def markdown_to_html(txt):
  from markdown import markdown
  return markdown(txt)
  • 使用示例

views

@app.route('/', methods=['POST', 'GET'])
def index():
  return render_template('index.html', body='# hello')
  • 模板中直接使用

{{ body|md|safe }}

二. 添加读取文件的功能

读取md文件, 并输出到html中

  • 定义读文件函数

def read_md(filename):
  with open(filename) as md_file:
    content = reduce(lambda x, y: x+y, md_file.readline())
  return content.decode('utf-8')
  • 上下文管理器

此时read_md函数可以全局使用

@app.context_processor
def inject_methods():
  return dict(read_md=read_md)
  • 可以在模板中调用函数

{{ read_md('test.md')|md|safe}}

关于怎么在flask框架中自定义过滤器就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

《怎么在flask框架中自定义过滤器.doc》

下载本文的Word格式文档,以方便收藏与打印。