1

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}}

1 Answer 1

3
  • 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>

Sign up to request clarification or add additional context in comments.

4 Comments

this is the reasonable way of doing this in a two step process but i guess this feature should have been implemented builtin or via plugins for common JS template engines.
Maybe some templates have actually a Markdown plugin, but the good thing about doing the two steps is the freedom to work with your Markdown parser of choice.
totally agreed using this approach you have the freedom of choosing your markdown parser and Template engine. Actually i want to go with EJS and marked instead of Mustache and commonMark. Any comment on this combo?
I like Marked but have no experience with EJS. I think the only important thing is to ensure that the template tag delimiters (e.g. {{...}}) of your engine are not valid Markdown. That is, don't use things like [...] as delimiters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.