Search code examples
ruby-on-railsckeditor

Rails how do I pass a rails variable to CKEditor config?


My scenario is that, some user who has the font_user role can use font, but others can't.

In ckeditor/config.js, I can't get any variable from Rails. How do I achieve this?

I have tried something like this:

  1. Modify config.js to config.js.erb.
  2. Add the following code.

    <% current_user.has_role?(font_user) %>
      XXXXX
    <% else %>
      XXXX
    <% end %>
    

    and I added the following method in application_controller.rb:

    helper_method :current_user
    

    But it seems config.js.erb can't get the current_user variable.


Solution

  • This is because asset JavaScript is compiled ones. Not each time a view is rendered. You should make use of unobstructive JavaScript. For example:

    View example:

    <div class="ckeditor" data-ckeditor-font="<%= current_user.has_role?(font_user) %>"></div>
    

    Alternatively (not checked):

    You could also use the #content_tag for this, although you have to check how to exactly pass along the data attributes. If I'm not mistaken:

    <% data = {
      'ckeditor-font': current_user.has_role?(font_user),
      # other data...
    } %>
    
    <%= content_tag :div, class: 'ckeditor', data: data %>
    

    But I currently don't have the setup to test the above code. So you'll have to check it yourself.


    Than in your asset JavaScript (CoffeeScript):

    initCkeditor = (element) ->
      fontUser = element.dataset.ckeditorFont == 'true'
    
      # further CKEditor initialization code...
    
    
    document.addEventListener 'turbolinks:load', ->
      document
        .querySelectorAll '.ckeditor'
        .forEach initCkeditor
    

    If you don't set the data-ckeditor-font attribute the code still works. Since element.dataset.ckeditorFont would return undefined, and undefined == 'true' is still false. (Keep in mind that the CoffeeScript == equals JavaScript ===.)

    See: