TL;DR - 我如何使用类似于 improved_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,并附加了用于高亮的标记。
唯一的问题是它不使用我的布局;毕竟,我只是读取文件并返回渲染后的字符串。正常的 markdown :foo
调用会涉及 Tilt 的过程。
我必须创建一个自定义的 Tilt 模板引擎来使其工作,还是有更简单的方法?
rackup config.ru
,它会发生,但如果我在Passenger上运行,则不会。 - Nathan LongPygments.start
应该可以解决它。果然,在添加了那一行代码后,Pygments工作正常了。 - matt