6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FlaskでMarkdownを表示する方法

Posted at

コード内に埋め込み

  • server.py
from flask import Flask, render_template, Markup
from markdown import markdown

app = Flask(__name__)

@app.route('/index')
def show_md():
  md = '#Hoge'
  md = Markup(markdown(md))
  return render_template('index.html', md=md)

if __name__ == '__main__':
  app.run(host='127.0.0.1', port=5500, debug=True)
  • index.html
<body>
  {{ md }}
</body>
  • markdownモジュールとMarkupオブジェクト組み合わせることでhtmlにレンダリングできます。

Markdownファイルから読み込み

  • main.md
# Hoge
- piyo
  • server.py
from flask import Flask, render_template, Markup
from markdown import markdown

def read_md() -> str:
  with open('./main.md', mode='r') as mdfile:
    mdcontent = mdfile.read()

  return Markup(markdown(mdcontent))

@app.route('/')
def index():
  content = read_md()
  return render_template('index.html', md=md)

if __name__ == '__main__':
  app.run(host='127.0.0.1', port=5500, debug=True)
  • index.html
<body>
  {{ md }}
</body>
  • read_mdメソッドでmarkdownファイルの文字列を読み取り、Markupオブジェクトでhtmlにレンダリングするようにします。
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?