bigsweater bigsweater - 7 months ago 136
Ruby Question

Rendering sections of ERb templates in Markdown with Middleman

I'm using Middleman (and Ruby, and Rails) for the first time, and I've hit a bit of a roadblock when it comes to rendering individual pages using Redcarpet as my markdown processor, and ERb for layout.

I want to use Markdown to style individual blocks of content, but each page will have more than one piece of content, uniquely styled.

Rather than using partials, is there a way to instantiate the Redcarpet renderer on multiple areas of the page? So in

index.html.erb
, there would be something like this:

<div class="grid5 container">
<% markdown do %>
# Some markdown
<% end %>
</div>

<section class="grid6">
<% markdown do %>
## More markdown
<% end %>
</section>


I've tried to build a helper based on several tutorials, but I'm just not that good at Rails yet.

Edit
My config.rb helper looks like:

module MD
def markdown(text)
Redcarpet.new(text).to_html
end
end

helpers MD


per ASCIIcasts, linked above, and my ERb template uses similar code to the above:

<span class="g6 pre3">
<% markdown do %>
...etc...
<% end %>


but I'm getting an error when I load the page:
ArgumentError at /about
wrong number of arguments (0 for 1)

Answer

You defined your markdown method to receive one parameter called text. But what you provide in your views is a block.

To make things work, you either change the way you call the markdown helper method in the view

<%= markdown 'this is some markdown text in here' %>

or you change the markdown helper to accept a block

def markdown
  Redcarpet.new(yield).to_html
end

P.S.: The Redcarpet syntax has changed a bit since the Railscast, so if you are using a more recent gem version, implementing it this way won't work.

Starting at least from 3.3.4, perhaps earlier, you have to create a specific renderer and then call render on it with the markdown as an argument, i.e.

def markdown
   Redcarpet::Render::XHTML.new.render(yield)
end

Up to date documentation can be found here: https://github.com/vmg/redcarpet