gpt4 book ai didi

sqlite - 在Flask应用程序中对查询的SQL使用markdown格式

转载 作者:行者123 更新时间:2023-12-03 17:36:13 25 4
gpt4 key购买 nike

在flask应用程序中,我正在从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,如果可能的话,我只想使用常规Markdown进行安装。

最佳答案

有两种选择:


您可以在将markdown传递给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)

您可以注册模板过滤器,然后在模板中使用它:

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


然后,您可以在模板中调用 markdown过滤器:

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

关于sqlite - 在Flask应用程序中对查询的SQL使用markdown格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18263671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com