gpt4 book ai didi

ruby-on-rails - 如何修改Redcarpet Markdown使其可以处理类?

转载 作者:行者123 更新时间:2023-12-04 04:20:10 25 4
gpt4 key购买 nike

我在Rails网站上使用Redcarpet Markdown。通常,我想将类(或其他属性)添加到段落,表或其他元素中,但不允许这样做。如果我用HTML替换markdown元素,那么我也需要用HTML替换内部markdown,这很麻烦。

例如,我想将class“table”添加到markdown table元素(以便获得Bootstrap的表样式),但是随后我需要用HTML替换Markdown表。

最简单的解决方案是什么?有没有一种简单的方法可以修改Markdown以便处理类?另外,有没有办法允许Markdown放在HTML元素内?

示例更新

我想将一个类添加到div,表或段落中,但仍将markdown保留在元素内。例如,我要生成以下HTML:

<p class="cool">
<b>Hello world</b> <a href="http://google.com">Google</a>
</p>

有2种可能的解决方案,但我不知道如何使用Redcarpet Markdown来解决:
  • 为类获取特殊的markdown语法,例如:
    {class: cool}**Hello world** [Google](http://google.com)
  • 允许Markdown在HTML元素中工作:
    <p class="cool"> **Hello world** [Google](http://google.com)</p>

  • 目前,我只是在不使用markdown的纯HTML中执行此类元素。但是我怎样才能使#1或#2正常工作呢?

    最佳答案

    您可以构建自己的渲染器(基于Redcarpet::Render::HTML),该渲染器将覆盖您感兴趣的自定义方法:

    Custom renderers are created by inheriting from an existing renderer. The built-in renderers, HTML and XHTML may be extended as such:

    # create a custom renderer that allows highlighting of code blocks
    class HTMLwithPygments < Redcarpet::Render::HTML
    def block_code(code, language)
    Pygments.highlight(code, :lexer => language)
    end
    end

    markdown = Redcarpet::Markdown.new(HTMLwithPygments, :fenced_code_blocks => true)

    But new renderers can also be created from scratch (see lib/redcarpet/render_man.rb for an example implementation of a Manpage renderer)


    <<snip>>

    The following instance methods may be implemented by the renderer:


    <<snip>>
    • table(header, body)

    <<snip>>
    • raw_html(raw_html)


    例如,要在原始HTML中启用markdown,建议您声明一个 <markdown>元素,您可以提取该元素并进行渲染( 警告-之前未经测试的代码):
    def raw_html(html)
    html.gsub(/<markdown>(.*)<\/markdown>/) { render $1 }
    end

    覆盖这些方法,以将所需的类添加到表中,或从原始HTML中的元素递归调用 render

    关于ruby-on-rails - 如何修改Redcarpet Markdown使其可以处理类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21445837/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com