加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何从Sinatra进行Github风格的Markdown渲染?

发布时间:2020-12-17 02:18:32 所属栏目:百科 来源:网络整理
导读:TL; DR – 如何使用better_markdown之类的东西:some_file来进行自定义渲染,但仍像往常一样渲染布局? 通常,要在Sinatra中渲染Markdown,您只需: markdown :some_file 但我想添加“屏蔽”语法高亮显示功能,就像你可以在Github README文件中那样做. ```rubycl
TL; DR – 如何使用better_markdown之类的东西:some_file来进行自定义渲染,但仍像往常一样渲染布局?

通常,要在Sinatra中渲染Markdown,您只需:

markdown :some_file

但我想添加“屏蔽”语法高亮显示功能,就像你可以在Github README文件中那样做.

```ruby
class Foo
  # etc
end
```

我已经部分工作了.

首先,我安装了Redcarpet并添加了一个自定义渲染类,它使用Pygments.rb进行语法高亮显示:

# 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

然后我在路线中使用它,像这样:

# Try to load any Markdown file specified in the URL
get '/*' do
  viewname = params[:splat].first

  if File.exist?("views/#{viewname}.md")

    # Uses my custom rendering class
    # The :fenced_code_blocks option means it will take,for example,# the word 'ruby' from ```ruby and pass that as the language
    # argument to my block_code method above  
    markdown_renderer = Redcarpet::Markdown.new(HTMLwithPygments,:fenced_code_blocks => true)

    file_contents = File.read("views/#{viewname}.md")
    markdown_renderer.render(file_contents)

  else
    "Nopers,I can't find it."
  end
end

这几乎可行. Markdown呈现为带有额外标记的HTML,用于突出显示.

唯一的问题是它不使用我的布局;毕竟,我只是读取一个文件并返回渲染的字符串.正常降价:foo调用将涉及Tilt过程.

我是否必须创建自定义Tilt模板引擎才能使其正常工作,还是有更简单的方法?

解决方法

您可以将任意选项传递给markdown方法(或任何其他渲染方法),它们将被传递给相关的Tilt模板. Tilt的Redcarpet模板在创建渲染器时查找任何提供的:渲染器选项,允许您指定自定义渲染器.

您还可以通过将它们作为第二个参数传递给set:markdown,:option =>来指定应该应用于所有降价调用的选项. :值.

但这并不是那么简单,因为Tilt的当前(已发布)版本无法正确检测您是否安装了Redcarpet 2.你可以明确告诉它:

# first ensure we're using the right Redcarpet version
Tilt.register Tilt::RedcarpetTemplate::Redcarpet2,'markdown','mkd','md'

# set the appropriate options for markdown
set :markdown,:renderer => HTMLwithPygments,:fenced_code_blocks => true,:layout_engine => :haml

现在任何对markdown的调用都应该使用自定义代码来代码块,并使用layout.haml作为布局.

(免责声明:我无法让Pygments工作(这会导致Sinatra每次都崩溃),但其他一切都在运行(我使用了一个简单的自定义block_code方法,只是添加了一条消息,所以我可以告诉它正在工作).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读