MultiFormat v0.1.2 MultiFormat View Source

MultiFormat is a helper for Phoenix.Router when working with multi format routes.

It allows routes to match for one or more extensions (or none) without having to manually define all of them and assigning pipelines with the matching plug :accepts, ….

Examples

The router:

defmodule MyAppWeb.Router do
  use MyAppWeb, :router
  # Use MultiFormat and supply default pipeline/ext pairs
  use MultiFormat, match_html: "", match_json: "json"

  pipeline :browser […]

  pipeline :match_html do # :html would conflict with the Phoenix.Controller imports
    plug(:accepts, ["html"])
  end

  pipeline :match_json do # :json would conflict with the Phoenix.Controller imports
    plug(:accepts, ["json"])
  end

  scope "/", MyAppWeb do
    # Use the default browser stack
    pipe_through(:browser)

    get("/", PageController, :index)

    # Does allow for `/test` and `/test.json` based in the default pairs
    # Does work with all the macros of Phoenix.Router
    get("/test", PageController, :index) |> multi()

    # Does allow only `/test2.json` based on the explicitly given pair
    get("/test2", PageController, :index) |> multi(match_json: "json")
  end
end

The controller:

defmodule MyAppWeb.PageController do
  use MyAppWeb, :controller

  # Overriding `action/2` makes matching on extensions easier
  def action(conn, _) do
    args = [conn, conn.params, conn.assigns]
    apply(__MODULE__, action_name(conn), args)
  end

  # Match for the extensionless html setup
  def index(conn, _params, %{match_ext: ""}) do
    render(conn, "index.html")
  end

  # Match for the json route
  def index(conn, _params, %{match_ext: "json"}) do
    render(conn, "index.json")
  end
end

Link to this section Summary

Link to this section Functions

Link to this macro multi(ast, opts \\ nil) View Source (macro)