InertiaPhoenix (inertia_phoenix v0.4.0)

Inertia Phoenix

Maintained by Devato

Tests Coverage Codacy Badge Hex.pm

Inertiajs Adapter for Elixir Phoenix 1.4 and 1.5

Usage

Getting started with Inertia.js in a few steps.

installation

Installation

Add to mix.exs:

{:inertia_phoenix, "~> 0.3.0"}

Add Plug to WEB_PATH/router.ex

  pipeline :browser do
    ...
    plug InertiaPhoenix.Plug
  end

Import render_inertia lib/active_web.ex

  def controller do
    quote do
      ...
      import InertiaPhoenix.Controller
    end
  end

configuration

Configuration

Add to config/config.exs

config :inertia_phoenix,
  assets_version: 1,          # default 1
  inertia_layout: "app.html"  # default app.html

render-from-controller

Render from Controller

NOTE: Flash data is automatically passed through to the page props.

def index(conn, _params) do
  render_inertia(conn, "Home", props: %{hello: "world"})

  # OR

  render_inertia(conn, "Home")
end

layout-templates

Layout/Templates

  • Doesn't require templates as Inertia Pages are templates.
  • div#app is rendered automatically.

An example layout:

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
  </head>
  <body>
    <%= @inner_content %>
    <script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
  </body>
</html>

shared-data-props

Shared Data / Props

Inertia.js Docs: https://inertiajs.com/shared-data

To share data:

InertiaPhoenix.share(:hello, fn -> :world end)
InertiaPhoenix.share(:foo, :baz)
InertiaPhoenix.share("user", %{name: "José"})

NOTE: props will overwrite shared data.

shared-data-custom-plug

Shared Data Custom Plug

For more complex data, you can create a custom plug.

Here's an example from the PingCRM app:

defmodule PingWeb.Plugs.InertiaShare do

  def init(default), do: default

  def call(conn, _) do
    InertiaPhoenix.share(conn, :auth, build_auth_map(conn))
  end

  defp build_auth_map(conn) do
    # build complex auth map
  end
end

Then add it to any pipeline that makes sense in myapp_web/router.ex:

pipeline :browser do
  ...
  plug PingWeb.Plugs.InertiaShare # put before main Plug
  plug InertiaPhoenix.Plug
end

handle-form-errors

Handle Form Errors

We can use Shared Data and the Phoenix Session to store server side errors.

See PingCRM for examples.

configure-axios

Configure Axios

XSRF-TOKEN cookie is set automatically.

To configure axios to use it by default, in app.js

import axios from "axios";
axios.defaults.xsrfHeaderName = "x-csrf-token";

Features

complete

Complete

in-progress

In Progress

See Issue Tracker

Example Apps

Contributing

Contribution guidelines for this project

Link to this section Summary

Link to this section Functions

Link to this function

assets_version()

Link to this function

inertia_layout()

Link to this function

path_with_params(map)

Link to this function

share(conn, key, val)

share()