In this blog post, I'll show you how you can render Markdown files (.md) in Flask and send the content into the front-end. To do this, we'll need to use a Flask extension called Flask-Markdown.
But first, what is Markdown?
Markdown is a lightweight markup language for creating formatted text using a plain-text editor.
... and, what about Flask?
As mentioned on the Pallets Projects website, "Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications" (this is the framework that powers this website).
So, how it works?
In this example, we'll render a Markdown file named temp.md and display the content in index.html.
This was tested in the following setup: Python 3.8.10, pip 20.0.2, Flask 2.0.2 and this is our app's folder structure:
app/
- templates/
- - index.html
- app.py
- temp.md
The first step, is to install the Flask-Markdown extension using pip:
pip install Flask-Markdown
When done, initialize your app and add the Markdown wrapper:
app.py
from flask import Flask, render_template
from flaskext.markdown import Markdown
# Init App
app = Flask(__name__)
Markdown(app)
@app.route('/')
def index():
# Read the Markdown file content
with open("temp.md") as md_file:
data = md_file.read()
return render_template('index.html', md_content = data)
if __name__ == '__main__':
app.run(debug=True)
Than, on the front-end side, filter the content into your Jinja template:
index.html
...
<div class="main-post">
{{ md_content|markdown }}
</div>
...
And that's it! I hope you find this blog post useful and, if you find any issue, please send me an email and I'll get back to you asap.