Search code examples
ruby-on-railsruby-on-rails-3wysiwygwysihtml5

How to integrate a packaged wysiwyg editor to my Rails app


I decided on using bootstrap-wysihtml5-rails, which is a packaged wysiwyg editor with Twitter bootstrap built in. My question is about how to "activate" the editor inside the form which I created with the form_for helper.

I have the following form which I would like to use the wysiwyg editor in:

<%= form_for(@question) do |f| %> 

  <%= f.label :title, "Title" %>
  <%= f.text_field :title %>

  <%= f.label :content, "Content" %>
  <%= f.text_area :content %> <!-- make this into wysiwyg editor -->

  <%= f.submit "Create question", class: "btn btn-large btn-primary" %>
<% end %>

The instructions noted to simply add the following:

<textarea id="some-textarea" class='wysihtml5' placeholder="Enter text ..."></textarea>

<script type="text/javascript">
  $('.wysihtml5').each(function(i, elem) {
    $(elem).wysihtml5();
  });
</script>

However, I am a bit lost about how I could toggle just my text_area section to make it into a wysiwyg. I looked into the Rails guide for form_for, but didn't see how I could insert javascript or even apply a css class to a particular field. Thanks for your help.


Solution

  • Add html class 'wysihtml5' to any text_area you want to implement the editor on.

    <%= f.text_area :content, class: 'wysihtml5' %>
    

    You can either paste the script inline as suggested, or put a global initializer at app/assets/javascipts/application.js:

    $(function() {
      $('.wysihtml5').each(function(i, elem) {
        $(elem).wysihtml5();
      });
    })