3

I have a markdown text saved in the databse and I want to show it as html to the user. I am using markdown.js as the processor and I pass the big multiline html string from rails to javascript by rendering a js.erb file from the controller.

But since it is multiline, the javascript becomes invalid. Is there any rails function which will take the whole string and assign it as a single line string to javascript variable. I cannot use html_safe also as some things might be escaped. What is the best way to handle markdown?

sample markdown

![enter image description here](https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRiOb7-0qeyx73XuXNqzLpxgXTlf5UMrMnF5zm-UKn3wLaXCW0UUw "enter image title here")
  1. Hello
3
  • If you render erb server-side anyway, why not have markdown rendered server-side as well? Commented Jul 31, 2015 at 17:28
  • can u tell me how to do that? Commented Jul 31, 2015 at 18:02
  • Added my advice as an answer. Commented Aug 1, 2015 at 12:47

1 Answer 1

2

If you render erb server-side anyway, you will probably be better rendering Markdown server-side as well. You can use Redcarpet for that.

  1. Add gem redcarpet to your Gemfile.
  2. Run bundle install
  3. Use it:

    text = "my _markdown_ *variable*"
    markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
    markdown.render(text)
    

It will be a good idea to save rendered HTML in the database, to save CPU time on re-rendering the same text every time you want to show it to client. So you can add something like this to your model:

class Article
  # let's say that model has 'source' attributes with Markdown
  # and we want to put resulting HTML into 'html' attribute
  before_save :markdown

  def markdown
    self.html = Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(source)
  end
end
Sign up to request clarification or add additional context in comments.

Comments

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.