How to render table with Redcarpet and Markdown
Asked Answered
P

2

19

I'm trying to render a table like this with Redcarpet

| header 1 | header 2 |
| -------- | -------- |
| cell 1   | cell 2   |
| cell 3   | cell 4   |

but it's not working.

Is it possible to render a table with Redcarpet ?

Pleinair answered 6/9, 2012 at 8:58 Comment(0)
W
35

Yes, you can render a table like that, but you have to enable the :tables option.

require 'redcarpet'
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, :tables => true)

text = <<END
| header 1 | header 2 |
| -------- | -------- |
| cell 1   | cell 2   |
| cell 3   | cell 4   |
END

puts markdown.render(text)

Outputs:

<table><thead>
<tr>
<th>header 1</th>
<th>header 2</th>
</tr>
</thead><tbody>
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</tbody></table>
Wiry answered 13/11, 2012 at 14:25 Comment(5)
Do you know how to set this option for haml helper? I tried set :markdown, :tables => true, but it didn't work.Quinate
@Alexey: did you find a way to activate it for HAML?Aguascalientes
@Quinate see my response (if it doesn't get deleted by moderators)Hallo
Do not use spaces in |------|------|Damal
Is it possible to render table without header? ` | cell 1 | cell 2 | | cell 3 | cell 4 | `Sepaloid
H
3

The accepted answer for table format is great. Trying to add this as a comment loses formatting. Yet adding it as an answer is somewhat questionable as well.

Anyway... this is in response to the question about using markdown table option with haml (in the context of Rails).

application_helper.rb

  def markdown(content)
    return '' unless content.present?
    @options ||= {
        autolink: true,
        space_after_headers: true,
        fenced_code_blocks: true,
        underline: true,
        highlight: true,
        footnotes: true,
        tables: true,
        link_attributes: {rel: 'nofollow', target: "_blank"}
    }
    @markdown ||= Redcarpet::Markdown.new(Redcarpet::Render::HTML, @options)
    @markdown.render(content).html_safe
  end

Then in a view (views/product_lines/show.html.haml):

= markdown(product_line.description)
Hallo answered 4/7, 2015 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.