how to access the yml file from application.js in rails?

Viewed 3711

I have a yml file and i need the keys to be used in the application.js file in the scripts. I cannot able to access it from the script. Please help me. I have the following lines in the initializer

APP_CONFIG = YAML.load_file("#{Rails.root}/config/filename.yml")[Rails.env]

and i have the following keys in my yml file

development:
  key1: 782364764527225794828437
  key2: sdjfbjs7e834284383984729
  key3: 73465365egfrf36462874727

and i access the keys in application.js file as

APP_CONFIG['key1']

but it seems to take nothing. But when i print the same thing in the view body as

<%= APP_CONFIG['key1'] %>

then it returns the value of the key1.

What should i do to access the value in application.js file. It also not works in the script body in the view itself.

3 Answers

I came to this question since I needed access to my Rails locale YAML from JS, more specifically the months array stored in there. My solution has been to create some HTML with the values I need with ERB and set display: none on the parent div (done here using bootstrap's d-none class).

In the locale YAML:

en:
  date:
    month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December]

In the view:

<ul class="d-none" id="months">
  <%= I18n.t('date.month_names').each do |month_name| %>
    <% if month_name.present? %>
      <li><%= month_name %></li>
    <% end %>
  <% end %>
</ul>

In the JS file:

const months = document.getElementById('months');
Related