The package can be installed by adding phoenix_gon to your list of dependencies in mix.exs:
def deps do
[{:phoenix_gon, "~> 0.4.0"}]
end- You need add plug to
lib/project/router.exafter plug:fetch_session.
defmodule Project.Router do
# ...
pipeline :browser do
# ...
plug :fetch_session
plug PhoenixGon.Pipeline
# ...
end
# ...
endPlug accepts options:
- `:env` - this option for hard overloading Mix.env.
- `:namespace` - namespace for javascript object in global window space.
- `:assets` - map for keeping permanent variables in javascript.
- `:camel_case` - if set to true, all assets names will be converted to camel case format on render.
- Add possibility to use view helper by adding
use PhoenixGon.Viewin templates inweb/views/layout_view.exfile:
defmodule Project.LayoutView do
# ...
import PhoenixGon.View
# ...
end- Add helper
render_gon_scriptto you layout in/web/templates/layout/app.html.eexbefore main javascript file:
# ...
<%= render_gon_script(@conn) %>
<script src="<%= static_path(@conn, "/js/app.js") %>"></script>
</body>Now you can read phoenix variables in browser console and javascript code.
For using gon in controllers just add:
defmodule Project.Controller do
# ...
import PhoenixGon.Controller
# ...
endAll controller variables are kept in assets map.
put_gon- Put variable to assets.update_gon- Update variable in assets.drop_gon- Drop variable in assets.get_gon- Get variable from assets.
Example:
def index(conn, _params) do
conn = put_gon(conn, controller: variable)
render conn, "index.html"
enddef index(conn, _params) do
conn = put_gon(conn, controller: variable)
redirect conn, to: "/somewhere.html"
endGon object is kept in window.
Now you can access to you variables in console:
// browser console
Gon.assets()
// Object {controller: "variable"}// Somewhere in javascript modules
window.Gon.assets()Phoenix env methods:
getEnv()- Returns current phoenix env.isDev()- Returns boolean if development env.isProd()- Returns boolean if production env.isCustomEnv(env)- Return bollean if custom env.
Assets variables methods:
assets()- Returns all variables setting in config and controllers.getAsset(key)- Returns variable by key.
Per default the Jason is used to encode JSON data, however this can be changed via the application configuration, eg:
config :phoenix_gon, :json_library, PoisonSpecial thanks to Andrey Soshchenko @getux.
The library is available as open source under the terms of the MIT License.