简体   繁体   中英

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

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.

You cannot execute ruby command in a Javascript file

You need to figure out some other way to load the values in application.js

Like initialize them in app/views/layouts/application.html.erb as a global variable

<script>
  var key = '<%= APP_CONFIG['key1'] %>';
</script>

and use it in any Javscript file

 window.onload=function(){ alert(key);};

You can not directly access your yml file content from JS file. What you can do is on your view page assign these keys to a js variable then it will be available to you for JS work

<script>
  var appConfigKeys = “<%= j APP_CONFIG.to_json.html_safe %>”;
  console.log(appConfigKeys);
</script>

If you want it to be available in other JS file as then you need to take help of global varibales.

<script>
  appConfigKeys = “<%= j APP_CONFIG.to_json.html_safe %>”;
  console.log(appConfigKeys);
</script>

Above solution will give you all the keys as a javascript hash If you need only first key, you can assign single key to a JS variable.

<script>
  appConfigKey = “<%= APP_CONFIG['key1'] %>”;
  console.log(appConfigKey);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM