hideto 发表于 2013-2-8 00:58:50

markItUp+rdiscount搭建Rails下可视化Markdown编辑器

markItUp是基于jQuery的可视化编辑器,支持Html,Textile,Wiki,Markdown,BBcode等多种标签。而且支持插件化替换各种标签和皮肤,UI效果很好。

自行下载jquery.js,然后从http://markitup.jaysalvat.com/downloads/下载jquery.markitup.js,Basic Markdown set和Simple and neutral skin。

在你的表单页面中加入相应的javascript和css文件,并用一段JavaScript初始化要用markItUp的Textarea:
<%=javascript_include_tag 'jquery' %><script type="text/javascript" src="/markitup/jquery.markitup.js"></script><script type="text/javascript" src="/markitup/sets/markdown/set.js"></script><link rel="stylesheet" type="text/css" href="/markitup/skins/simple/style.css" /><link rel="stylesheet" type="text/css" href="/markitup/sets/markdown/style.css" /><script language="javascript">$(document).ready(function() {    $('#textarea').markItUp(mySettings);});</script>

效果图:
http://dl.iteye.com/upload/attachment/371770/1ad465ef-7e07-3846-b4ef-6c5217a25d07.png

保存Markdown文本到数据库后如何转化成HTML格式展现在页面上?
安装rdiscount即可:
gem install rdiscount
然后在show页面上:
<%= raw RDiscount.new(@question.content).to_html %>
注意:需要对用户恶意输入的<script>等标签做额外处理。比如仿照whitelist html tags做一个blacklist的helper方法:
DISALLOWED_TAGS = %w(script iframe) unless defined?(DISALLOWED_TAGS)def blacklist(html)    # only do this if absolutely necessary    if html.index("<")      tokenizer = HTML::Tokenizer.new(html)      new_text = ""      while token = tokenizer.next      node = HTML::Node.parse(nil, 0, 0, token, false)      new_text << case node                  when HTML::Tag                      if DISALLOWED_TAGS.include?(node.name)                        node.to_s.gsub(/</, "<")                      else                        node.to_s                      end                  else                      node.to_s.gsub(/</, "<")                  end      end      html = new_text    end    htmlend
然后就可以这样show content了:
<%= raw blacklist RDiscount.new(@question.content).to_html %>

实现preview功能:
1. 编辑set.js
previewParserPath:'/questions/preview',
2. 编辑routes.rb
match 'questions/preview' => 'questions#preview'
3. 编辑controller
def previewrender :text => RDiscount.new(params[:data]).to_htmlend
这样就能成功请求后台的rdiscount来parse markdown标签生成preview了,效果:
http://dl.iteye.com/upload/attachment/371772/a4e7f4b4-88cc-3362-b7af-c42d6289092a.png
页: [1]
查看完整版本: markItUp+rdiscount搭建Rails下可视化Markdown编辑器