How to pass and render a ruby variable in a markdo

2019-07-23 07:56发布

问题:

I'm using the gem "redcarpet". And I have a markdown file. I want to be able to render it with some ruby variables. Something like this:

 # my_file.md

 ###Something
 fdafdsfdsfds

 ---

 <% for n in my_numbers do %>
     <%= n %>
 <% end %>

What's the proper way to do something like this? How can I pass and render a ruby variable?

回答1:

You can use the erb library which is included in ruby, but you have to require it:

require 'erb'
require 'redcarpet'

input = File.read "./file.md"

markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true, tables: true)

output = markdown.render ERB.new(input).result(binding)

File.open("output.html", "w") { |f| f.write output }

You can customize the markdown renderer by referencing the redcarpet readme



标签: ruby markdown