Using Markdown with Ratpack
Groovy's SimpleTemplateEngine provides a very simple way to create dynamic HTML from templates. It is lightweight enough that it is compatible with almost any templating engine. I started playing around with it because I wanted to find a way to create some dynamic client code and wanted something more expressive and compact than regular HTML but not as complex as a JSP. Using Markdown and SimpleTemplateEngine together allowed me to hit that sweet spot.
Overview of Markdown
Markdown was created by John Gruber (of Daring Fireball fame) and Aaron Schwartz to allow one to easily translate a shorthand written in text files to HTML. It uses a limited set of special characters to designate headings, listings, figures, links and code blocks. It's the type of system that allows the formatting of an article to get out of your way and not disrupt your flow. Below is a sample Markdown file.
A First Level Header
This is just a regular paragraph.
<% num.times { %>
<%= it %>. <%= it+1 %> squared = <%= (it+1)&42;(it+1) %>
<% } %>
The following are code blocks and will print as is:
<br/> means break
<hr/> means horizontal rule
In addition to parsers/translators for almost every programming language imaginable, Markdown is one of the formats that PanDoc can convert to a number of other formats including DocBook and PDF. For this post, I used MarkdownJ.
Using Markdown in A Route
Ratpack receives a request for an endpoint which retrieves the Markdown template, injects the given params, and evaluates the Groovy code contained in it. The resulting text is passed to MarkdownJ where it is converted into HTML and pushed into the response. The code snippet below shows how it all works.
import com.petebevin.markdown.*
//... truncated code
get("/") {
def m = new MarkdownProcessor()
def p = render 'template.md', [num:4]
m.markdown(p)
}