我能实现这个插件的功能,譬如blog资源,有title和content字段,对content字段渲染
<p>
<b>Content:</b>
<%=code(@blog.content, :theme => "blackboard", :lang => "ruby", :line_numbers => true)%>
</p>
<b>Content:</b>
<%=code(@blog.content, :theme => "blackboard", :lang => "ruby", :line_numbers => true)%>
</p>
这样会将content里的内容都当做ruby代码来渲染,但是如果是content字段有很多代码和文字内容,该怎么处理。。请教中。
----=======
解答:
content中代码块是在<code lang="language"></code>标签中的。所以对content进行扫描,将代码块进行渲染,然后返回整体显示结果。具体过程就是:
1.在application_helper.rb中
def syntax_highlight_and_markdown(text, options = {})
text_pieces = text.split(/(<c0de>|<c0de lang="[A-Za-z0-9_-]+">|<c0de lang='[A-Za-z0-9_-]+'>|<\/c0de>)/)
in_pre = false
language = nil
text_pieces.collect do |piece|
if piece =~ /^<c0de( lang=(["'])?(.*)\2)?>$/
language = $3
in_pre = true
nil
elsif piece == "</c0de>"
in_pre = false
language = nil
nil
elsif in_pre
code(piece.strip, :lang => language,:theme => "blackboard", :line_numbers => true)
else
markdown(piece, options)
end
end
end
def markdown(text, options = {})
if options[:strip]
BlueCloth.new(strip_tags(text.strip)).to_html
else
BlueCloth.new(text.strip).to_html
end
end
text_pieces = text.split(/(<c0de>|<c0de lang="[A-Za-z0-9_-]+">|<c0de lang='[A-Za-z0-9_-]+'>|<\/c0de>)/)
in_pre = false
language = nil
text_pieces.collect do |piece|
if piece =~ /^<c0de( lang=(["'])?(.*)\2)?>$/
language = $3
in_pre = true
nil
elsif piece == "</c0de>"
in_pre = false
language = nil
nil
elsif in_pre
code(piece.strip, :lang => language,:theme => "blackboard", :line_numbers => true)
else
markdown(piece, options)
end
end
end
def markdown(text, options = {})
if options[:strip]
BlueCloth.new(strip_tags(text.strip)).to_html
else
BlueCloth.new(text.strip).to_html
end
end
然后在视图中:
<%= syntax_css("blackboard")%>
...
<%= syntax_highlight_and_markdown @post.content %>
...
<%= syntax_highlight_and_markdown @post.content %>
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/122144,如需转载请自行联系原作者