Adding Markdown support to Clabango templates

If you're coming to Clojure web development from Django, you might be interested in Clabango by Dan Larkin.  Clabango is a Clojure templating library modeled after Django's.  It supports several of the Django filters and tags (including the can't-live-without include, block, if, for and extends), but also allows you to extend them by writing your own.

On my current side project, I wanted to add support for writing text entries in markdown and have the templates output the text in html.  Thanks to markdown-clj by Dmitri Sotnikov, this was very simple.

In a namespace for my project's filters, I required markdown-clj, then passed Clabango's body argument to md-to-html-string:

(ns logbook.filters
  (:require [clabango.filters :as filter]
            [markdown.core :as md]))

(filter/deftemplatefilter "markdown" [node body args]
  (when body (md/md-to-html-string body)))

Note that the return value of the deftemplatefilter is a string, rather than the map that Clabango's current examples demonstrate. There is a difference between the source on Github and the binary on Clojars.

Now wherever I need to convert text from markdown to html in a Clabango template, I pass the text to the new markdown filter:
    {% for entry in entries %}
  • {{ entry.title|markdown }}
  • {% endfor %}
I was really impressed by how simple and easy this was.  Thanks guys!

Update:  Dmitri has released Selmer.

3 comments:

Unknown said...

Glad you like markdown-clj :)

If you're using Selmer you could add a markdown filter as follows:

(add-filter! :markdown (fn [s] [:safe (md-to-html-string s)]))

not that Selmer escapes the injected content by default. You have to put the content you don't wish escaped in a vector starting with the :safe keyword.

Alternatively you can chain the filter with the safe filter:

{{content|markdown|safe}}

mj said...

Thanks for the comment Dmitri. I've been using Luminus (and Selmer) for my latest project--I even ran into the "safe" issue earlier and went with the filter.

I'm really enjoying the work you're doing. Thanks a lot for Luminus and Selmer!

Unknown said...

Really glad it's useful. I've ran into a lot of annoyances when I started developing web apps in Clojure, so I figured I'd make life easier for others. :)