Markdown in Umbraco

Tuesday, December 2, 2014 1:11 PM umbraco

Umbraco 7.2 ships with a builtin Markdown property editor. There is no corresponding builtin datatype but it is very easy to create one in the Developers/DataTypes section. Add a property of that type to a content type and bam, you have a nice Markdown editor in the backend.

Then, rendering the content of that field should be as simple as:


Alas, that renders the original Markdown markup as a string. Turns out that Umbraco does not ship with a Markdown engine and does not know how to convert that markup to html.

Using a Markdown engine

There are many Markdown engines available for .NET. This website uses MarkdownDeep which you can install via NuGet (if your website is a Visual Studio solution) or just copy in your bin directory.

Rendering now looks like:

  var val = Model.GetPropertyValue<string>("markdown");
  var md = new MarkdownDeep.Markdown();
  var html = new MvcHtmlString(md.Transform(val));

So you can go and copy that code in all your views.

Better create a converter

Repeating that code in all the views can be tiring and prone to errors. And then you'll want to switch to another engine and you'll have to modify all the views. We could create a "helper" method of some sort—which we'd still need to call in all our views.

A much more elegant solution consists in creating a property value converter for that property type:

public class MarkdownConverter : PropertyValueConverterBase
  public override bool IsConverter(PublishedPropertyType propertyType)
    return propertyType.PropertyEditorAlias.InvariantEquals(Constants.PropertyEditors.MarkdownEditorAlias);

  public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
    var stringSource = source as string;

    if (string.IsNullOrWhiteSpace(stringSource))
      return null;

    var md = new MarkdownDeep.Markdown();
    var html = md.Transform(stringSource);
    return new MvcHtmlString(html);

All you need is to drop that code anywhere in your solution (or in App_Code) and Umbraco will use it anytime you get the value of the property. So now, you have one central place where conversion takes place, and you can write the following Razor code which will output the converted html:


Which means that we have abstracted the conversion in an elegant and simple way.

comments powered by Disqus