Search code examples
javascriptmarkdowntemplate-engine

Using markdown in JavaScript template engine


How to use markdown(or any other markup -> HTML language) in a template. Is it possible with available JavaScript template engines?

Template:

This is a *sample* question?
![some_image](image/path)
{{screenshot}}

Solution

    • Run first your template engine.
    • Pass the rendered HTML to the markdown parser.
    • Run your markdown parser.

    I leave you a snippet that uses Mustache as template engine and the JavaScript implementation of CommonMark for Markdown.

    In the links above you can find the code that I used for the example.

    function loadUser() {
      var template = $('#template').html();
      var rendered = Mustache.render(template, {
        name: "*Luke*"
      });
      $('#target').html(rendered);
    
      var reader = new commonmark.Parser();
      var writer = new commonmark.HtmlRenderer();
      var parsed = reader.parse($('#target').html());
      var result = writer.render(parsed);
      $('#target').html(result);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/3.0.0/mustache.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/commonmark/0.28.1/commonmark.min.js"></script>
    
    <body onload="loadUser()">
      <div id="target">Loading...</div>
      <script id="template" type="x-tmpl-mustache">
    This is an example of **markdown** in a *template*.  
    Hello {{ name }}!
      </script>
    </body>