LoginSignup
11
11

More than 3 years have passed since last update.

【rails】Markdown記法で投稿を表示する方法をやってみる

Last updated at Posted at 2020-04-17

railsで投稿した内容をマークダウン形式で入力しても、表示できるようにしました。
また、言語ごとにハイライトをつけることもできます。

gemをインストール

以下を追加

Gemfile
# マークダウン形式で表示するためのgem
gem 'redcarpet', '~> 2.3.0'
# シンタックスハイライトに対応させるためのgem
gem 'coderay'

その後、bundle install

application_helper.rbに記述

app/helpers/application_helper.rb
module ApplicationHelper
  # マークダウン形式で記入するためにrequire
  require "redcarpet"
  require "coderay"

  class HTMLwithCoderay < Redcarpet::Render::HTML
    def block_code(code, language)
        language = language.split(':')[0]

        case language.to_s
        when 'rb'
            lang = 'ruby'
        when 'yml'
            lang = 'yaml'
        when 'css'
            lang = 'css'
        when 'html'
            lang = 'html'
        when ''
            lang = 'md'
        else
            lang = language
        end

        CodeRay.scan(code, lang).div
    end
  end

  # マークダウンを可能にするメソッド
  def markdown(text)
    html_render = HTMLwithCoderay.new(filter_html: true, hard_wrap: true)
    options = {
        autolink: true,
        space_after_headers: true,
        no_intra_emphasis: true,
        fenced_code_blocks: true,
        tables: true,
        hard_wrap: true,
        xhtml: true,
        lax_html_blocks: true,
        strikethrough: true
    }
    markdown = Redcarpet::Markdown.new(html_render, options)
    markdown.render(text)
  end
end

show.html.erbに記述

app/views/posts/show.html.erb
<div class="クラス名">
  <%= markdown(@post.content).html_safe %>
</div>

@post.contentは一例です。
表示したい箇所に <%= markdown(モデル名.カラム名).html_safe %> を追加します。

editページで編集してみる

rails s で動かしてから、
用意した自分のアプリ内の編集ページで投稿をマークダウン形式で編集してみます。
スクリーンショット 2020-04-17 14.47.10.png

「```ruby」のようにするとハイライトができます。
バッククオート3つの隣に言語(拡張子)を書く要領です。

「`」←これは私の使ってるmacだとshiftキー+optionキー+_(アンダーバー)で入力できます。
詳しいマークダウン記法はこちらのサイトにわかりやすく載っています。
https://qiita.com/Qiita/items/c686397e4a0f4f11683d

showページで確認

スクリーンショット 2020-04-17 14.36.43.png

参考

https://qiita.com/shu_0115/items/476a51cb4751515f3ac2
https://qiita.com/hkengo/items/978ea1874cf7e07cdbfc

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11