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)*(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)
}
Links
About James Williams
James Williams is a Senior Software Engineer for Taulia based in Silicon Valley and a frequent conference speaker. He is a co-creator of the Griffon project, a rich desktop framework for Java applications. He and his team WalkIN, created a product on a coach bus while riding to SXSW, and were crowned winners of StartupBus 2011. He is the author of the upcoming book "Learning HTML5 Game Programming..." for Addison-Wesley. He blogs at http://jameswilliams.be/blog and tweets as @ecspike.
More About James »NFJS, the Magazine
2011-12-01 00:00:00.0 Issue Now AvailableBDD and REST
by Brian SlettenMocks and Stubs in Groovy Tests
by Kenneth KousenAlgorithms for Better Text Search Results
by John GriffinKnowns and Unknowns of Scrum and Agile
by Brian Tarbox