nmbrone / gonex

Get your Phoenix variables in your Javascript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Gonex - get your Phoenix variables in your Javascript

Actions Status Hex version badge

Gonex is a super simple implementation of gon but for Phoenix projects and it's a convenient way to send some data from your controller to your JavaScript.

Installation

The package can be installed by adding gonex to your list of dependencies in mix.exs:

def deps do
  [
    {:gonex, "~> 0.1.0"}
  ]
end

Usage

First in your layout view:

defmodule MyAppWeb.LayoutView do
  use MyAppWeb, :view
  
  # Import Gonex view helpers
  import Gonex.View
  
  def render("app.html", assigns) do
    ~E"""
    <!-- ... -->
    <%= render_gon(assigns.conn, "myAppGon") %>
    <!-- ... -->
    """
  end
end

Then in your controller:

defmodule MyAppWeb.PageController do
  use MyAppWeb, :controller
  
  # Import Gonex controller helpers.
  # Alternatively you can import this in your MyAppWeb :controller definition 
  # and make Gonex available within all of your controllers
  import Gonex.Controller
  
  def index(conn, _params) do
    conn
    |> put_gon(greeting: "Hello, World!") # put something useful here
    |> render("index.html")
  end
end

Finally in you JavaScript:

alert(window.myAppGon.greeting); // "Hello, World!"

Sometimes you will need to have a basic (or initial) set of variables across all of your views. This can be easily achieved with the custom plug:

defmodule MyAppWeb.PutGonPlug do
  def init(opts), do: opts
  
  def call(conn, _opts) do
    Gonex.Controller.put_gon(conn, %{
      env: Application.get_env(:my_app, :env),
      locale: Gettext.get_locale(MyAppWeb.Gettext)
    })
  end
end

Then in your router:

defmodule MyAppWeb.Router do
  use MyAppWeb, :router

  pipeline :browser do
    # ...
    plug MyAppWeb.PutGonPlug
    # ...
  end
end

Documentation

The docs can be found at https://hexdocs.pm/gonex.

About

Get your Phoenix variables in your Javascript

License:MIT License


Languages

Language:Elixir 100.0%