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

[url=http://markitup.jaysalvat.com/home/]markItUp[/url]是基于jQuery的可视化编辑器,支持Html,Textile,Wiki,Markdown,BBcode等多种标签。而且支持插件化替换各种标签和皮肤,UI效果很好。

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

在你的表单页面中加入相应的javascript和css文件,并用一段JavaScript初始化要用markItUp的Textarea:
[code]
<%=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>
[/code]

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

保存Markdown文本到数据库后如何转化成HTML格式展现在页面上?
安装[url=https://github.com/rtomayko/rdiscount]rdiscount[/url]即可:
[code]
gem install rdiscount
[/code]
然后在show页面上:
[code]
<%= raw RDiscount.new(@question.content).to_html %>
[/code]
注意:需要对用户恶意输入的<script>等标签做额外处理。比如仿照[url=http://hideto.iteye.com/blog/82583]whitelist html tags[/url]做一个blacklist的helper方法:
[code]
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(/</, "&LT;")
else
node.to_s
end
else
node.to_s.gsub(/</, "&LT;")
end
end

html = new_text
end
html
end
[/code]
然后就可以这样show content了:
[code]
<%= raw blacklist RDiscount.new(@question.content).to_html %>
[/code]

实现preview功能:
1. 编辑set.js
[code]
previewParserPath: '/questions/preview',
[/code]
2. 编辑routes.rb
[code]
match 'questions/preview' => 'questions#preview'
[/code]
3. 编辑controller
[code]
def preview
render :text => RDiscount.new(params[:data]).to_html
end
[/code]
这样就能成功请求后台的rdiscount来parse markdown标签生成preview了,效果:
[img]http://dl.iteye.com/upload/attachment/371772/a4e7f4b4-88cc-3362-b7af-c42d6289092a.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值