在烧瓶应用程序中查询的SQL上使用markdown格式

时间:2013-08-15 23:38:59

标签: sqlite flask markdown

在烧瓶应用程序中,我正在从sqlite数据库中检索一些条目,以便在我的html页面上显示,代码如下:

@app.route('/')
def index():
    db = get_db()
    cur = db.execute('select title, text from entries order by id desc')
    entries = cur.fetchall()
    return render_template('index.html', entries=entries)

我想使用markdown格式化内容。我已经安装了markdown,并希望在我的sql查询中使用它,就像下面在原始数据上使用它一样。

import markdown
from flask import Flask
from flask import render_template
from flask import Markup

app = Flask(__name__)
@app.route('/')

def index():
  content = """
Chapter
=======

Section
-------

* Item 1
* Item 2
"""
  content = Markup(markdown.markdown(content))
  return render_template('index.html', **locals())

app.run(debug=True)

当在html模板中提取时,将章节/节/项目标记为向下标记下来。 我不想安装Flask-Markdown 如果可能,我只想通过常规降价执行此操作。

1 个答案:

答案 0 :(得分:2)

有两种选择:

  1. 您可以在将标记下传到render_template之前渲染标记:

    @app.route('/')
    def index():
        db = get_db()
        cur = db.execute('select title, text from entries order by id desc')
        entries = [Markup(markdown(entry) for entry in cur.fetchall()]
        return render_template('index.html', entries=entries)
    
  2. 您可以注册模板过滤器,然后在模板中使用它:

    @app.template_filter("markdown")
    def render_markdown(markdown_text):
        return Markup(markdown(markdown_text))
    

    然后,在您的模板中,您只需拨打markdown过滤器:

    {% for entry in entries %}
    <article>
        {{entry | markdown}}
    </article>
    {% endfor %}