How to include Markdown with Freemarker in Dropwizard

November 5, 2012 | Comments
Tags: Dropwizard Freemarker HowTo Markdown


One common problem that web developers face is the elegant handling of rich text received from their users which should be rendered as HTML. Obviously, accepting raw HTML from unknown sources is a major security risk. Fortunately, this problem has been solved through the use of Markdown which requires only an easily readable text document from your users. If you’re looking for a portable rich text solution for documentation and requirements specifications then Markdown is a great solution.

In order to include Markdown into your own projects you need only use a suitable Markdown parser, and an easy to use one is pegdown. This is available in Maven central under the following co-ordinates:

<dependency>
  <groupId>org.pegdown</groupId>
  <artifactId>pegdown</artifactId>
  <version>1.1.0</version>
</dependency>

In order to use it in Dropwizard just add it to the model that backs your View like this:

public String getHtml() throws IOException {

  // Hard coded but could come from anywhere
  String markdown = "## Example Markdown\n" +
    "\n" +
    "This is a paragraph\n" +
    "\n" +
    "This is another\n" +
    "\n" +
    "[This is a link](http://example.org)";

  // New processor each time due to pegdown not being thread-safe internally
  PegDownProcessor processor = new PegDownProcessor();

  // Return the rendered HTML
  return processor.markdownToHtml(markdown);

}

Then you simply include the Markdown output into your FreeMarker template like so:

<#-- @ftlvariable name="" type="org.example.MyView" -->
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>

${html}

</body>
</html>

Hope this helps someone!

Tweet

Related Posts

Useful? Consider a small donation: 1KzTSfqjF2iKCduwz59nv2uqh1W2JsTxZH

Got an opinion? Comments are welcome!

Want more? Take a look at the following:

Dropwizard with Ember Data demo
Dropwizard with OpenID
How to implement a RuntimeExceptionMapper for Dropwizard
MultiBit Merchant: Implementing HMAC authentication in Dropwizard
How to deploy a Dropwizard project to Heroku
MultiBit Merchant: Deployment Driven Design?
How to create a deterministic JAR
Preventing Dependency Chain Attacks in Maven
How to deploy dynamic sites with git
How to deploy static sites with git
How to recover your bitcoins from a failed hard drive
How to build a Builder
How to accept bitcoins on your blog with no code

comments powered by Disqus