flask自定义一个过滤器例子: markdown文件读取和展示

除了一些内置的join length safe等过滤器外, flask还提供了自定义过滤器的功能.

一. 自定义一个mardown过滤器

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

  1. 安装库
pip install Markdown==2.3.1
  1. 自定义过滤器

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

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

    • views
@app.route('/', methods=['POST', 'GET'])
def index():
    return render_template('index.html', body='# hello')
  • 模板中直接使用
{{ body|md|safe }}
二. 添加读取文件的功能

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

  1. 定义读文件函数
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')
  1. 上下文管理器

此时read_md函数可以全局使用

@app.context_processor
def inject_methods():
    return dict(read_md=read_md)
  1. 可以在模板中调用函数
{{ read_md('test.md')|md|safe}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值