Scalahansolo
Scalahansolo

Reputation: 3035

Converting string to html

Currently I have a system in place where I have users that fill out a textarea with markdown text and store it in the server. Than when a client loads a page I want that markdown text converted to readable HTML. As it stands I have the markdown converting to a long HTML string, but have no way of injecting the html into my page as it is just a string right now.

This is what I have tried so far...

Coffeescript File

Template.messages.convertMsg = (message) ->
    doc = document.createElement('div')
    doc.innerHTML = marked(message)
    doc.getElementsByTagName( 'a' )

HTML File

<div class="chat-message-contents">{{convertMsg message}}</div>

An example html string might be...

'<li><a href="#adding-two">Adding Two</a>'

Upvotes: 0

Views: 612

Answers (2)

Hubert OG
Hubert OG

Reputation: 19544

The easiest way is to add a standard showdown package:

mrt add showdown

Then simply write:

<template name="...">
  {{#markdown}}{{message}}{{/markdown}}
</template>

Note that white spaces matter in markdown, so if you did

{{#markdown}}
  {{message}}
{{/markdown}}

The first line of message would be indented, which would cause a bad formatting.


Alternatively, if you're confident that you prefer your own Markdown parser, use triple brace or Handlebars.SafeString. Also a good idea would be to create your helper globally, so that other templates can display markdown as well.

UI.registerHelper('convertMsg', function(options) {
  var html = marked(options.fn(this));
  return new Handlebars.SafeString(html);
});

Upvotes: 1

Christian Fritz
Christian Fritz

Reputation: 21374

Maybe I'm missing something, but can't you just place the html string in a triple-bracket?

<div class="chat-message-contents">{{{convertMsg message}}}</div>

This would make sure that the html is not escaped, i.e., it is rendered.

Upvotes: 1

Related Questions