Add an HTML Page to Elixir Phoenix

From ElixirBlocks
Jump to: navigation, search

This tutorial describes how to render an HTML page in Elixir Phoenix. This tutorial does not use Liveview.

Create the Route

In app/appweb/router.ex set a route. In the example below, the route is a get request and the endpoint is /landing. Assign a Controller. In the code below, this is PageController. In the third argument, set an atom that will be the name of the HTML page. In this case, it is index.

    get "/landing", PageController, :index


The code below shows you where to place the above code.

  scope "/", AppWeb do
    pipe_through :browser

    get "/landing", PageController, :index

  end


Create Controller

in app/appweb/ create a directory named controllers.

In this directory create a controller file named page_controller.ex. The name of the controller file needs to mirror the name in our code. PageController hence the name page_controller.ex

In the page_controller.ex file place the following code:

defmodule AppWeb.PageController do
  use AppWeb, :controller

  def index(conn, params) do

   
    render(conn, :index, data: "Hello World")
  end
end


Create the HTML View file

In the controllers directory create a file named page_html. This files prefix needs to continue to reflect the controller name.

In the file type this code:

defmodule AppWeb.PageHTML do
  use AppWeb, :html

  embed_templates "page_html/*"
end


The above code is setting the directory that Phoenix will reference its HTML template files for this route.

Under the controllers directory, create a folder named page_html.

In this directory create a file named index.html.heex and copy the following code into it:

<div>THis is a working page</div>
<div> <%=@data%> </div>


Launch the server and you will see the page render with the HTML template used.

mix phx.server