LoginSignup
1
1

More than 5 years have passed since last update.

HighVoltageを使ってRailsでmarkdownからページを動的生成

Posted at

参考

やりたいこと

  • そこそこ文章量のあるほぼ静的なページで、個別にController作るのだるいし、DBに入れるまでもないようなページ作りたい
  • ルーティング書くのもだるいのでURLから判別してレンダリングして欲しい
  • md内でhelperは使いたい

やり方

下準備

gem 'high_voltage'
gem 'rdiscount'
config/initializers/high_voltage.rb
HighVoltage.configure do |config|
  config.content_path = 'stashes/'
end
config/initializers/markdown_handler.rb
require 'rdiscount'

module MarkdownHandler
  def self.erb
    @erb ||= ActionView::Template.registered_template_handler(:erb)
  end

  def self.call(template)
    compiled_source = erb.call(template)
    "RDiscount.new(begin;#{compiled_source};end).to_html"
  end
end

ActionView::Template.register_template_handler :md, MarkdownHandler

/blog/:post の場合

routes.rb
get 'blog/:post', to: 'high_voltage/pages#show', id: 'blog'
app/views/stashes/blog.html.erb
<% post = "#{params[:post].gsub('-', '_')}"  %>

<%= render("stashes/blog/#{post}").html_safe %>
app/views/stashes/blog/_test.md
# TEST

<%= Time.current %>
<%= link_to 'root', root_path %>

これで http://localhost:3000/blog/test を開くと
現在時刻とルートへのリンクのあるページが表示できる。
違うページは同様に app/views/stashes/blog/_xxx.md を追加していけばよい。

1
1
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
1
1