23
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

東京理科大学Advent Calendar 2016

Day 18

Railsにマークダウンのリアルタイムプレビューを実装する

Last updated at Posted at 2016-12-24

サンプルコードのclassはBootstrapのclassです。

Vue.jsとmarked.jsを読み込む

application.html.erb
<!-- Realtime preview -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.10/vue.js'></script>  
<script src='https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.js'></script>  

formを編集

_form.html.erb

  <%= form_for @post, :url => {:action => :create} do |f| %>
    <div class="form-group">
      <%= f.text_field :title , class: 'form-control', placeholder: 'タイトルを入力してください'%>
    </div>
    <div class="form-group">
      <div id='editor'>
        <textarea name="post[content]" class="form-control" rows="20" v-model='input' debounce='50'></textarea>
        <div v-html='input | marked'></div>
      </div>
    </div>
  <% end %>


_form.html.erbにscript追加

_form.html.erb
<script type="text/javascript">
  window.onload = function() {
    new Vue({
      el: '#editor',
      data: {
        input: '<%== j @post.content %>',
      },
      filters: {
        marked: marked,
      },
    });
  };
</script>

input: '<%== j @post.content %>'はeditの時にpost.contentをフォームに入れるためです。

デザイン

CSSでうまくやってください

まとめ

これだけでtextareaに入れた文字がリアルタイムで表示されます

CDNじゃなくてGemで入れろよ!

すみません。いつか更新します。。。

たぶんこれです
adambutler/vuejs-rails

scriptじゃなくてapp/assets/javascript配下に書けよ!

すみません。いつか更新します。。。

23
17
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
23
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?