Phoenix v1.1.4 Phoenix.Controller

Controllers are used to group common functionality in the same (pluggable) module.

For example, the route:

get "/users/:id", MyApp.UserController, :show

will invoke the show/2 action in the MyApp.UserController:

defmodule MyApp.UserController do
  use MyApp.Web, :controller

  def show(conn, %{"id" => id}) do
    user = Repo.get(User, id)
    render conn, "show.html", user: user
  end
end

An action is just a regular function that receives the connection and the request parameters as arguments. The connection is a Plug.Conn struct, as specified by the Plug library.

Connection

A controller by default provides many convenience functions for manipulating the connection, rendering templates, and more.

Those functions are imported from two modules:

  • Plug.Conn - a bunch of low-level functions to work with the connection

  • Phoenix.Controller - functions provided by Phoenix to support rendering, and other Phoenix specific behaviour

Rendering and layouts

One of the main features provided by controllers is the ability to do content negotiation and render templates based on information sent by the client. Read render/3 to learn more.

It is also important to not confuse Phoenix.Controller.render/3 with Phoenix.View.render/3 in the long term. The former expects a connection and relies on content negotiation while the latter is connection-agnostic and typically invoked from your views.

Plug pipeline

As with routers, controllers also have their own plug pipeline. However, different from routers, controllers have a single pipeline:

defmodule MyApp.UserController do
  use MyApp.Web, :controller

  plug :authenticate, usernames: ["jose", "eric", "sonny"]

  def show(conn, params) do
    # authenticated users only
  end

  defp authenticate(conn, options) do
    if get_session(conn, :username) in options[:usernames] do
      conn
    else
      conn |> redirect(to: "/") |> halt()
    end
  end
end

Check Phoenix.Controller.Pipeline for more information on plug/2 and how to customize the plug pipeline.

Options

When used, the controller supports the following options:

  • :namespace - sets the namespace to properly inflect the layout view. By default it uses the base alias in your controller name

  • :log - the level to log. When false, disables controller logging

Overriding action/2 for custom arguments

Phoenix injects an action/2 plug in your controller which calls the function matched from the router. By default, it passes the conn and params. In some cases, overriding the action/2 plug in your controller is a useful way to inject certain argument to your actions that you would otherwise need to fetch off the connection repeatedly. For example, imagine if you stored a conn.assigns.current_user in the connection and wanted quick access to the user for every action in your controller:

def action(conn, _) do
  apply(__MODULE__, action_name(conn), [conn,
                                        conn.params,
                                        conn.assigns.current_user])
end

def index(conn, _params, user) do
  videos = Repo.all(user_videos(user))
  # ...
end

def delete(conn, %{"id" => id}, user) do
  video = Repo.get!(user_videos(user), id)
  # ...
end

Summary

Functions

Performs content negotiation based on the available formats

Returns the action name as an atom, raises if unavailable

A plug that may convert a JSON response into a JSONP one

Clears all flash messages

Returns the controller module as an atom, raises if unavailable

Deletes any CSRF token set

Returns the endpoint module as an atom, raises if unavailable

Fetches the flash storage

Gets the CSRF token

Returns a previously set flash message or nil

Returns a message from flash by key

Returns the request format, such as “json”, “html”

Sends html response

Sends JSON response

Retrieves the current layout

Retrieves current layout formats

Enables CSRF protection

Persists a value in flash

Puts the format in the connection

Stores the layout for rendering

Sets which formats have a layout when rendering

Stores the layout for rendering if one was not stored yet

Stores the view for rendering if one was not stored yet

Put headers that improve browser security

Stores the view for rendering

Sends redirect response to the given url

Render the given template or the default template specified by the current action with the given assigns

Renders the given template and assigns based on the conn information

Returns the router module as an atom, raises if unavailable

Scrubs the parameters from the request

Sends text response

Retrieves the current view

Returns the template name rendered in the view as a string (or nil if no template was rendered)

Functions

accepts(conn, accepted)

Specs

accepts(Plug.Conn.t, [binary]) ::
  Plug.Conn.t |
  no_return

Performs content negotiation based on the available formats.

It receives a connection, a list of formats that the server is capable of rendering and then proceeds to perform content negotiation based on the request information. If the client accepts any of the given formats, the request proceeds.

If the request contains a “_format” parameter, it is considered to be the format desired by the client. If no “_format” parameter is available, this function will parse the “accept” header and find a matching format accordingly.

It is important to notice that browsers have historically sent bad accept headers. For this reason, this function will default to “html” format whenever:

  • the accepted list of arguments contains the “html” format

  • the accept header specified more than one media type preceeded or followed by the wildcard media type “*/*

This function raises Phoenix.NotAcceptableError, which is rendered with status 406, whenever the server cannot serve a response in any of the formats expected by the client.

Examples

accepts/2 can be invoked as a function:

iex> accepts(conn, ["html", "json"])

or used as a plug:

plug :accepts, ["html", "json"]
plug :accepts, ~w(html json)

Custom media types

It is possible to add custom media types to your Phoenix application. The first step is to teach Plug about those new media types in your config/config.exs file:

config :plug, :mimes, %{
  "application/vnd.api+json" => ["json-api"]
}

The key is the media type, the value is a list of formats the media type can be identified with. For example, by using “json-api”, you will be able to use templates with extension “index.json-api” or to force a particular format in a given URL by sending “?_format=json-api”.

After this change, you must recompile plug:

$ touch deps/plug/mix.exs
$ mix deps.compile plug

And now you can use it in accepts too:

plug :accepts, ["html", "json-api"]
action_name(conn)

Specs

action_name(Plug.Conn.t) :: atom

Returns the action name as an atom, raises if unavailable.

allow_jsonp(conn, opts \\ [])

Specs

allow_jsonp(Plug.Conn.t, Keyword.t) :: Plug.Conn.t

A plug that may convert a JSON response into a JSONP one.

In case a JSON response is returned, it will be converted to a JSONP as long as the callback field is present in the query string. The callback field itself defaults to “callback” but may be configured with the callback option.

In case there is no callback or the response is not encoded in JSON format, it is a no-op.

Only alphanumeric characters and underscore are allowed in the callback name. Otherwise an exception is raised.

Examples

# Will convert JSON to JSONP if callback=someFunction is given
plug :allow_jsonp

# Will convert JSON to JSONP if cb=someFunction is given
plug :allow_jsonp, callback: "cb"
clear_flash(conn)

Clears all flash messages.

controller_module(conn)

Specs

controller_module(Plug.Conn.t) :: atom

Returns the controller module as an atom, raises if unavailable.

delete_csrf_token()

Deletes any CSRF token set.

endpoint_module(conn)

Specs

endpoint_module(Plug.Conn.t) :: atom

Returns the endpoint module as an atom, raises if unavailable.

fetch_flash(conn, opts \\ [])

Fetches the flash storage.

get_csrf_token()

Gets the CSRF token.

get_flash(conn)

Returns a previously set flash message or nil.

Examples

iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn)
%{"info" => "Welcome Back!"}
get_flash(conn, key)

Returns a message from flash by key.

Examples

iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn, :info)
"Welcome Back!"
get_format(conn)

Returns the request format, such as “json”, “html”.

html(conn, data)

Specs

html(Plug.Conn.t, iodata) :: Plug.Conn.t

Sends html response.

Examples

iex> html conn, "<html><head>..."
json(conn, data)

Specs

json(Plug.Conn.t, term) :: Plug.Conn.t

Sends JSON response.

It uses the configured :format_encoders under the :phoenix application for :json to pick up the encoder module.

Examples

iex> json conn, %{id: 123}
layout(conn)

Specs

layout(Plug.Conn.t) :: {atom, String.t} | false

Retrieves the current layout.

layout_formats(conn)

Specs

layout_formats(Plug.Conn.t) :: [String.t]

Retrieves current layout formats.

protect_from_forgery(conn, opts \\ [])

Enables CSRF protection.

Currently used as a wrapper function for Plug.CSRFProtection and mainly serves as a function plug in YourApp.Router.

Check get_csrf_token/0 and delete_csrf_token/0 for retrieving and deleting CSRF tokens.

put_flash(conn, key, message)

Persists a value in flash.

Returns the updated connection.

Examples

iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn, :info)
"Welcome Back!"
put_format(conn, format)

Puts the format in the connection.

See get_format/1 for retrieval.

put_layout(conn, layout)

Specs

put_layout(Plug.Conn.t, {atom, binary} | binary | false) :: Plug.Conn.t

Stores the layout for rendering.

The layout must be a tuple, specifying the layout view and the layout name, or false. In case a previous layout is set, put_layout also accepts the layout name to be given as a string or as an atom. If a string, it must contain the format. Passing an atom means the layout format will be found at rendering time, similar to the template in render/3. It can also be set to false. In this case, no layout would be used.

Examples

iex> layout(conn)
false

iex> conn = put_layout conn, {AppView, "application.html"}
iex> layout(conn)
{AppView, "application.html"}

iex> conn = put_layout conn, "print.html"
iex> layout(conn)
{AppView, "print.html"}

iex> conn = put_layout :print
iex> layout(conn)
{AppView, :print}

Raises Plug.Conn.AlreadySentError if the conn was already sent.

put_layout_formats(conn, formats)

Specs

put_layout_formats(Plug.Conn.t, [String.t]) :: Plug.Conn.t

Sets which formats have a layout when rendering.

Examples

iex> layout_formats conn
["html"]

iex> put_layout_formats conn, ["html", "mobile"]
iex> layout_formats conn
["html", "mobile"]

Raises Plug.Conn.AlreadySentError if the conn was already sent.

put_new_layout(conn, layout)

Specs

put_new_layout(Plug.Conn.t, {atom, binary | atom} | false) :: Plug.Conn.t

Stores the layout for rendering if one was not stored yet.

Raises Plug.Conn.AlreadySentError if the conn was already sent.

put_new_view(conn, module)

Specs

put_new_view(Plug.Conn.t, atom) :: Plug.Conn.t

Stores the view for rendering if one was not stored yet.

Raises Plug.Conn.AlreadySentError if the conn was already sent.

put_secure_browser_headers(conn, opts \\ [])

Put headers that improve browser security.

It sets the following headers:

* x-frame-options - set to SAMEORIGIN to avoid clickjacking
  through iframes unless in the same origin
* x-content-type-options - set to nosniff. This requires
  script and style tags to be sent with proper content type
* x-xss-protection - set to "1; mode=block" to improve XSS
  protection on both Chrome and IE

Custom headers may also be given.

put_view(conn, module)

Specs

put_view(Plug.Conn.t, atom) :: Plug.Conn.t

Stores the view for rendering.

Raises Plug.Conn.AlreadySentError if the conn was already sent.

redirect(conn, opts)

Sends redirect response to the given url.

For security, :to only accepts paths. Use the :external option to redirect to any URL.

Examples

iex> redirect conn, to: "/login"

iex> redirect conn, external: "http://elixir-lang.org"
render(conn, template_or_assigns \\ [])

Specs

render(Plug.Conn.t, Dict.t | binary | atom) :: Plug.Conn.t

Render the given template or the default template specified by the current action with the given assigns.

See render/3 for more information.

render(conn, template, assigns)

Specs

render(Plug.Conn.t, module, binary | atom) :: Plug.Conn.t
render(Plug.Conn.t, binary | atom, Dict.t) :: Plug.Conn.t

Renders the given template and assigns based on the conn information.

Once the template is rendered, the template format is set as the response content type (for example, an HTML template will set “text/html” as response content type) and the data is sent to the client with default status of 200.

Arguments

  • conn - the Plug.Conn struct

  • template - which may be an atom or a string. If an atom, like :index, it will render a template with the same format as the one returned by get_format/1. For example, for an HTML request, it will render the “index.html” template. If the template is a string, it must contain the extension too, like “index.json”

  • assigns - a dictionary with the assigns to be used in the view. Those assigns are merged and have higher precedence than the connection assigns (conn.assigns)

Examples

defmodule MyApp.UserController do
  use Phoenix.Controller

  def show(conn, _params) do
    render conn, "show.html", message: "Hello"
  end
end

The example above renders a template “show.html” from the MyApp.UserView and sets the response content type to “text/html”.

In many cases, you may want the template format to be set dynamically based on the request. To do so, you can pass the template name as an atom (without the extension):

def show(conn, _params) do
  render conn, :show, message: "Hello"
end

In order for the example above to work, we need to do content negotiation with the accepts plug before rendering. You can do so by adding the following to your pipeline (in the router):

plug :accepts, ["html"]

Views

By default, Controllers render templates in a view with a similar name to the controller. For example, MyApp.UserController will render templates inside the MyApp.UserView. This information can be changed any time by using render/3, render/4 or the put_view/2 function:

def show(conn, _params) do
  render(conn, MyApp.SpecialView, :show, message: "Hello")
end

def show(conn, _params) do
  conn
  |> put_view(MyApp.SpecialView)
  |> render(:show, message: "Hello")
end

put_view/2 can also be used as a plug:

defmodule MyApp.UserController do
  use Phoenix.Controller

  plug :put_view, MyApp.SpecialView

  def show(conn, _params) do
    render conn, :show, message: "Hello"
  end
end

Layouts

Templates are often rendered inside layouts. By default, Phoenix will render layouts for html requests. For example:

defmodule MyApp.UserController do
  use Phoenix.Controller

  def show(conn, _params) do
    render conn, "show.html", message: "Hello"
  end
end

will render the “show.html” template inside an “app.html” template specified in MyApp.LayoutView. put_layout/2 can be used to change the layout, similar to how put_view/2 can be used to change the view.

layout_formats/2 and put_layout_formats/2 can be used to configure which formats support/require layout rendering (defaults to “html” only).

render(conn, view, template, assigns)

Specs

render(Plug.Conn.t, atom, atom | binary, Dict.t) :: Plug.Conn.t
router_module(conn)

Specs

router_module(Plug.Conn.t) :: atom

Returns the router module as an atom, raises if unavailable.

scrub_params(conn, required_key)

Specs

scrub_params(Plug.Conn.t, String.t) :: Plug.Conn.t

Scrubs the parameters from the request.

This process is two-fold:

  • Checks to see if the required_key is present
  • Changes empty parameters of required_key (recursively) to nils

This function is useful to remove empty strings sent via HTML forms. If you are providing an API, there is likely no need to invoke scrub_params/2.

If the required_key is not present, it will raise Phoenix.MissingParamError.

Examples

iex> scrub_params(conn, "user")
text(conn, data)

Specs

text(Plug.Conn.t, String.Chars.t) :: Plug.Conn.t

Sends text response.

Examples

iex> text conn, "hello"

iex> text conn, :implements_to_string
view_module(conn)

Specs

view_module(Plug.Conn.t) :: atom

Retrieves the current view.

view_template(conn)

Specs

view_template(Plug.Conn.t) :: binary | nil

Returns the template name rendered in the view as a string (or nil if no template was rendered).