I want to have some of my partials as markdown snippets. What is the easiest way to render them using the standard rails erb templating?
Ideally, I'd like to do something like this:
If I have a partial in app/views/_my_partial.md.erb:
My awesome view
===============
Look, I can **use** <%= language %>!
which I reference from a view like so:
<%= render "my_partial", :language => "Markdown!" %>
I want to get output that looks like this:
<h1>My awesome view</h1>
<p>Look, I can <strong>use</strong> Markdown!</p>
Piling on the solutions already presented, this is an interpolation-ary way in Rails 3 to render a pure Markdown file in a view from a partial without unnecessary indentation using Haml's
:markdown
filter and the RDiscount gem. The only catch is that your Markdown file is a Haml file, but that shouldn't matter for someone like a copy person.In Gemfile:
In app/views/my_page.html.haml
In app/views/_my_partial.html.haml
If you didn't need the
:language
variable passed in to the markdown file, you could do away altogether with your Markdown being a Haml file:In app/views/my_page.html.haml
In app/views/_my_partial.md
Don't like those pesky underscores on your Markdown files?
In app/views/my_page.html.haml
In app/views/my_markdown.md
You can use embedded markdown in Rails 5. Embedded markdown is based on the solution provided by Jacob above
Add these two lines to your application's Gemfile:
gem 'redcarpet' gem 'emd'
bundle install.
Then create a view
app/view/home/changelog.html.md
and paste your markdown in that.md
file.Generate a home controller using the following command
rails generate controller home
At your route.rb, add this line:
get '/changelog', :to 'home#changelog'
That's all. Visit http://localhost:3000/changelog to see your rendered markdown
Source: http://github.com/ytbryan/emd
Here is a version similar to @Jacob's but using Redcarpet.
Full credit to lencioni who posted this in this gist.
And if you'd like to evaluate erb:
I just released a markdown-rails gem, which handles
.html.md
views.You cannot chain it with Erb though -- it's only for static views and partials. To embed Ruby code, you'd have to use tjwallace's solution with
:markdown
.Turns out, the Right Way (tm) to do this is using
ActionView::Template.register_template_handler
:lib/markdown_handler.rb:
If you
require 'markdown_handler'
in yourconfig/application.rb
(or an initializer), then any view or partial can be rendered as Markdown with ERb interpolation using the extension.html.md
:app/views/home/index.html.md:
app/controllers/home_controller.rb:
Not a pure markdown solution but you can use HAML filters to render markdown, as well as other markup languages.
For example, in
app/views/_my_partial.html.haml
: