DEV Community

Rudra Narayan
Rudra Narayan

Posted on • Edited on

Rendering markdown from Flask

This post was originally posted on https://rudra.dev/posts/rendering-markdown-from-flask

In this post I am going to plug about a cool trick(probably useless) that I discovered geeking around the internet.

I was building a tiny microservice which would let the client side application securely authenticate with GitHub. After writing the only required API, I wanted to render the README.md file on the index page.

So I planned to convert markdown to html and serve the resultant string everytime we hit the index.

Let's go hacking

Required packages



pip3 install Flask markdown


Enter fullscreen mode Exit fullscreen mode

app.py



import markdown
from flask import Flask
import markdown.extensions.fenced_code

app = Flask(__name__)


@app.route("/")
def index():
    readme_file = open("README.md", "r")
    md_template_string = markdown.markdown(
        readme_file.read(), extensions=["fenced_code"]
    )

    return md_template_string


if __name__ == "__main__":
    app.run()


Enter fullscreen mode Exit fullscreen mode

In the above snippet we are using Flask(my current favorite) as the web framework, Python-Markdown to convert markdown files to HTML, and fenced_code extension to support code blocks.

And it looked something like this

render markdown

Not quite there yet!

Well even though Richard Stallman remains my hero, fortunately I do not share his taste on web design. So without over-engineering our little snippet I thought of adding syntax highlighting with pygments and CodeHilite extension.

Let's generate css for syntax highlighting using pygments



from pygments.formatters import HtmlFormatter

formatter = HtmlFormatter(style="emacs",full=True,cssclass="codehilite")
css_string = formatter.get_style_defs()


Enter fullscreen mode Exit fullscreen mode

ow we need to append the css_string to the markdown converted HTML string.



md_css_string = "<style>" + css_string + "</style>"
md_template = md_css_string + md_template_string
return md_template


Enter fullscreen mode Exit fullscreen mode

Alternatively we can use pygments-css repository to get pre-generated CSS files.

Let's see how the final version looks!

Alt Text

Much better if you ask me!

Gimme the code!

Here is the full source code running on Glitch.

Feel free to remix and play around. Adios!

Top comments (1)

Collapse
 
aaichert profile image
Andre Aichert

For those just copying code: don't forget to add the codehilite extension to the first snippet if you want to make it work.

extensions=["fenced_code", "codehilite"]