---
title: "markItUp+rdiscount搭建Rails下可视化Markdown编辑器"
author: "hideto"
date: "2010-12-21T17:48:43Z"
tags: []
categories: ["编程语言"]
slug: "markitup-rdiscount-rails-markdown"
draft: false
lastmod: "2010-12-21T19:27:42Z"
id: 848500
url: "https://hideto.iteye.com/blog/848500"
---

[markItUp](http://markitup.jaysalvat.com/home/)是基于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](https://github.com/rtomayko/rdiscount)即可：

```

gem install rdiscount

```

然后在show页面上：

```

<%= raw RDiscount.new(@question.content).to_html %>

```

注意：需要对用户恶意输入的<script>等标签做额外处理。比如仿照[whitelist html tags](http://hideto.iteye.com/blog/82583)做一个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(/</, "&LT;")
                      else
                        node.to_s
                      end
                    else
                      node.to_s.gsub(/</, "&LT;")
                    end
      end

      html = new_text
    end
    html
  end

```

然后就可以这样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 preview
  render :text => RDiscount.new(params[:data]).to_html
end

```

这样就能成功请求后台的rdiscount来parse markdown标签生成preview了，效果：
![](http://dl.iteye.com/upload/attachment/371772/a4e7f4b4-88cc-3362-b7af-c42d6289092a.png)