Js access yml variables

Is there a way to pass data set in yml files to js? I was curious if anyone has tackled this before, or is this pretty greenfield.

Yes. Here is an example of array of objects:

var geodata = [
  <% data.geodata.each_with_index do |geo, index| %>
  {
    'name' : <%= "'#{geo.name}'" %>,
    'lat' : <%= "'#{geo.lat}'" %>,
    'lng' : <%= "'#{geo.lng}'" %>,
  }<%= ',' unless index == data.geodata.length-1 %>
  <% end %>
];

If you use this in a JavaScript file, just make sure it has a js.erb file extension. I used it in a template to mock up bootstrapped data.

Sweet, I will have to give that a try and let you know. Thank you.

1 Like

@jng5 here is how I finally structured this.

  1. require the keyval library in my application js
  2. setup the variables.js.erb template

var global_data = new keyval();
<% data.company.each_with_index do |(key, value), position| %>
global_data.set(<%= “’#{key.downcase}’” %>, escape(<%= “’#{value}’” %>));
<% end %>
<% data.product.each_with_index do |(key, value), position| %>
global_data.set(<%= “’#{key.downcase}’” %>, escape(<%= “’#{value}’” %>));
<% end %>

Currently I have 2 data bags and will have more down the road. This setup allowed me to use the same bags for the ruby and emberjs part of my application.

I can access the keys like:

console.log(global_data.get('short_name').v);
console.log(unescape(global_data.get('short_name').v));

References: