from flask import Flask, render_template
import markdown
app = Flask(__name__)
@app.route('/')
def index():
with open('example.md', 'r') as file:
content = file.read()
html_content = markdown.markdown(content)
return render_template('index.html', content=html_content)
if __name__ == '__main__':
app.run(debug=True)
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown with Flask</title>
</head>
<body>
<div>
{{ content | safe }}
</div>
</body>
</html>
- Import the necessary modules:
Flask
, render_template
from Flask, and markdown
. - Create a Flask web application instance.
- Define a route for the root URL ('/'). This route will render an HTML page that displays the content of a Markdown file.
- Inside the route function, open a Markdown file (
example.md
in this case) and read its content. - Use the
markdown
module to convert the Markdown content to HTML. - Render the HTML template (
index.html
) and pass the HTML content as a variable. - In the HTML template, use the
safe
filter to render the HTML content without escaping. - Run the Flask application if the script is executed directly.