How to define gon variables in the rails view (slim files)?

932 Views Asked by At

I have a number of views where I need to pass ruby/rails arrays to javascript/jquery code in my project. I'm using the gon gem which works fine when I define the gon variables in the controller code, but how can I assign the variable in the view code(slim file)?

For example if we have the following code in the controller:

gon.test_var = "hello there"

and then try to alert it in my jquery/javascript code as shown below:

$(document).ready(function() {
  alert(gon.test_var);
});

It works fine.

How can I achieve the same thing by defining the variable in the view file (I should be able to define gon.test_var in the slim file)?

Edit: Please note that the values we assign to the variable are ruby variables and not static string or number.

2

There are 2 best solutions below

1
On

Set:

- name = 'smth'
= current_gon.gon["name"] = name

Get:

= current_gon.gon["name"]

0
On

The official way is to use the global setting of Gon:

- Gon.global.push test_var: your_value

and use the global data:

gon.global.test_var

another way is to pass gon as an instance variable. So in your controller your assign

@gon = gon

then in your view, you can use

- @gon.push test_var: your_value
- @gon.test_var2 = your_value # old syntax