Daily Dev Notes 2024/05/29
Last week I implemented a Markdown Previewer using HTMX, which was fairly rudimentary - it just POST
ed the contents of a textarea
element to a Django view that returned the converted content, which HTMX swapped into the preview div
element.
While this worked pretty well, I wasn't overly keen of the constant stream of POST
requests that were being streamed to the server. I had played with some different delays to reduce the number of requests - but the higher the delay, the less interactive it felt. I also didn't want to implement a client-side markdown renderer with JavaScript, because I wanted to use the same renderer in the previewer that I'm using on this site.
I remembered seeing a raft of activity when Pyscript was released, but had forgotten all about it since I didn't have a use case for it. Well, now Pyscript has this great web-based IDE where you can not only develop your scripts, but also publish them to the world. To say it was easy to implement this, is an understatement. Within an hour of looking at the docs, I had a fully working, published-on-the-web Markdown Previewer, using client-side Python scripting in the browser. You can find that initial effort here.
After being so impressed with how easy it was to get up and running, I decided to replace my HTMX-based version with the Pyscript implementation. It needed just 3 things to work...
Include the Pyscript JavaScript file in the head of the page:
<script type="module" src="https://pyscript.net/releases/2024.5.2/core.js"></script>
In the body of the page, include some standard HTML with the only interesting thing being the
py-keyup="preview"
attribute on the textarea element. This tells Pyscript to run thepreview
function on akeyup
event.<div class="row"> <div class="col"> <textarea id="content" py-keyup="preview" class="form-control" rows="20" style="font-family: monospace"></textarea> </div> <div class="col"> <div id="preview"></div> </div> </div>
Include the following snippet of Python in a
<script>
tag as if you were typing inline JavaScript. As you can probably guess, theconfig
attribute tells Pyscript that themarkdown
andpygments
packages are required.<script type="py" config='{"packages":["markdown", "pygments"]}'> import markdown from pyscript import document md = markdown.Markdown(extensions=["fenced_code", "codehilite", "tables"], output_format="html") def preview(event): input = document.querySelector("#content").value output = document.querySelector("#preview") output.innerHTML = md.convert(input) md.reset() </script>
That's it! You can see a screenshot of it below as I've got it implemented here. At the moment it's only doing the preview, nothing else. But ultimately, I want to integrate this into DJ Press Admin site for composing blog posts.