If you need to send some data to your JavaScript, and you don’t want to do this the long way through views and parsing:
An example of typical use
First, check out an excellent and detailed example and reasons to use Gon in a RailsCast by Ryan Bates.
When you need to send some data from your Rails controller to your JavaScript code, typically you might do something like this:
- Have the data ready in controller code assigned to a variable.
- In the Rails view for this action, you would use the data from that variable via data attributes—or write some JavaScript right in the view code.
- Next, in your JavaScript code, you would parse data attributes—or just use the data as is if you went with the inline JavaScript way.
With gon, you start with some configuration. Add gon
to your Gemfile, and put a single tag in your layout. Now, you can:
- Pass variables using
or, using a new syntax:
gon.variable_name = variable_value
gon.push({ :user_id => 1, :user_role => "admin" }) gon.push(any_object) # any_object with respond_to? :each_pair
- Within your JavaScript code, the variable would be accessible as
gon.variable_name
That’s it!
See also
You can easily renew data in your variables via AJAX with gon.watch.
gon-sinatra is available for using with Sinatra. There is also Jbuilder, Rabl, and Rabl-Rails support available.
There is a port for .Net MVC, called NGon.
For Phoenix, the Elixir web framework, check PhoenixGon.