【问题标题】:How to render table with Redcarpet and Markdown如何使用 Redcarpet 和 Markdown 渲染表格
【发布时间】:2012-09-06 08:58:26
【问题描述】:

我正在尝试使用 Redcarpet 呈现这样的表格

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

但它不起作用。

是否可以使用 Redcarpet 渲染表格?

【问题讨论】:

    标签: markdown redcarpet


    【解决方案1】:

    是的,您可以呈现这样的表格,但您必须启用 :tables 选项。

    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)
    

    输出:

    <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>
    

    【讨论】:

    • 你知道如何为haml helper 设置这个选项吗?我试过set :markdown, :tables =&gt; true,但没用。
    • @Alexey:你有没有办法为 HAML 激活它?
    • @Alexey 看到我的回复(如果它没有被版主删除)
    • 不要在|------|------|中使用空格
    • 是否可以在没有标题的情况下呈现表格? ` |单元格 1 |单元格 2 | |单元格 3 |单元格 4 | `
    【解决方案2】:

    表格格式的公认答案很棒。尝试将其添加为评论会丢失格式。然而,将其添加为答案也有些问题。

    无论如何...这是对有关在 haml 中使用 markdown table 选项的问题的回答(在 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
    

    然后在一个视图中(views/product_lines/show.html.haml):

    = markdown(product_line.description)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2019-11-04
      相关资源
      最近更新 更多