Markdown

Markdown Content#

So far, and as in most examples online, the content field is a single plain string, which is pretty limited regarding rich content.

Markdown is a popular lightweight markup language used for creating and formatting content on the web. One of the key reasons why Markdown is good for content is that it provides a simple and intuitive syntax that is easy to learn and use.

With just a few basic commands, you can format text, add headings, create lists, and insert links and images. Additionally, Markdown files are easy to read and edit with any text editor, making it a flexible and versatile option for content creators of all levels.

Moreover, as you’ll see, including an embedded Markdown editor in the web form is simple. Overall, Markdown offers a streamlined and accessible way to create and format content for the web, and easy to store in a single database field.

Install the Python markdown package, and nh3, which is explained below:

pip install markdown nh3

Add them to the non_ver_reqs.txt file:

non_ver_reqs.txttext
fastapi[standard]
pydantic-settings
pytest
sqlmodel
alembic
markdown
nh3
pip freeze > requirements.txt

Update the blogpost_get_view function to convert the content field from Markdown to HTML. You’ll need to import markdown and nh3 too:

web/views/blog_views.pypython
import markdown  # NEW
import nh3  # NEW
web/views/blog_views.pypython
@router.get('/blog/{id}', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_get_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):

    post = get_blogpost_by_id_api(id=id, session=session)
    markdown_content = nh3.clean(markdown.markdown(post.content))  # NEW

    context = {
        "page": "blog",
        "post": post,
        "markdown": markdown_content  # NEW
    }

    return templates.TemplateResponse(request, 'blogpost.html', {'context': context})

In the template, update the content variable to be markdown, and mark it as safe, so Jinja2 outputs the HTML rather than escaping it:

web/templates/blogpost.htmljinja
{{ context.markdown|safe }}
Why nh3?

Markdown allows raw HTML, so without sanitising, anyone who can write a post could include a <script> tag that runs in every reader’s browser (cross-site scripting). |safe tells Jinja2 to trust the HTML completely. nh3 removes anything dangerous, such as scripts, event handlers like onclick and javascript: links, while keeping the normal formatting Markdown produces (headings, links, images, code and so on). For example, the Markdown <script>alert(1)</script> **bold** ends up as just <p><strong>bold</strong></p>. Only ever use |safe on HTML you’ve sanitised.

You can now add or edit a post and use Markdown in the content! To make this an even richer experience, check out https://github.com/Ionaru/easy-markdown-editor.

You can download the CSS and JavaScript directly:

curl -L -o web/static/css/easymde.min.css https://unpkg.com/easymde/dist/easymde.min.css
curl -L -o web/static/js/easymde.min.js https://unpkg.com/easymde/dist/easymde.min.js

Include them in both blog_create.html and blog_update.html. You might think to add these in the _base.html, which you could, however do you want to load such content on every page when it’s only ever needed in two templates?

Also, update the content form field to include the editor:

web/templates/blog_create.htmljinja
{% extends "_base.html" %}

{% block content %}

<link rel="stylesheet" href="/static/css/easymde.min.css">
<script src="/static/js/easymde.min.js"></script>

            {# ... CONTENT OMITTED ... #}

            <div class="row control-group">
                <div class="form-group col-xs-12 floating-label-form-group controls">
                    <label>Content</label>
                    <textarea class="form-control" placeholder="Content" id="markdown_content" name="content"></textarea>
                    <script>
                        var easyMDE = new EasyMDE({element: document.getElementById('markdown_content'), forceSync: true});
                    </script>
                    <p class="help-block text-danger"></p>
                </div>
            </div>

            {# ... CONTENT OMITTED ... #}
web/templates/blog_update.htmljinja
{% extends "_base.html" %}

{% block content %}

<link rel="stylesheet" href="/static/css/easymde.min.css">
<script src="/static/js/easymde.min.js"></script>

            {# ... CONTENT OMITTED ... #}

            <div class="row control-group">
                <div class="form-group col-xs-12 floating-label-form-group controls">
                    <label>Content</label>
                    <textarea class="form-control" placeholder="Content" id="markdown_content" name="content">{{ context.post.content }}</textarea>
                    <script>
                        var easyMDE = new EasyMDE({element: document.getElementById('markdown_content'), forceSync: true});
                    </script>
                    <p class="help-block text-danger"></p>
                </div>
            </div>

            {# ... CONTENT OMITTED ... #}

Two details in the <textarea>:

  • It no longer has the required attribute. EasyMDE hides the real textarea and shows its own editor, and browsers refuse to submit a form when a hidden required field is empty, without showing why. forceSync: true keeps the hidden textarea up to date as you type.
  • The closing </textarea> is on the same line. Anything between the tags, including line breaks and indentation, becomes part of the content.