Displaying Posts

Building an app with Phoenix : part 5 of 9 published on Aug 10, 2015

Now since we have Posts and have added our first Post using the console. Let’s display the list of Posts with Phoenix.

Create the Route

We first need to add a /posts route to our Phoenix router.

# /web/router.ex
  ...
  scope "/", Readdit do
    pipe_through :browser # Use the default browser stack

    get "/", PageController, :index
    get "/posts", PostsController, :index
  end
  ...

Create the Controller

Our controller is where we will accept an incoming connection and the parameters. We will then retrieve the Posts and pass them to the view.

# /web/controllers/posts_controller.ex
defmodule Readdit.PostsController do
  use Readdit.Web, :controller

  plug :action

  def index(conn, _params) do
    posts = Readdit.Repo.all(Readdit.Post)
    render conn, "index.html", posts: posts
  end
end

Retrieving the posts is done by:

posts = Readdit.Repo.all(Readdit.Post)

You can also retrieve the posts in the more common way of:

posts = Readdit.Post |> Readdit.Repo.all

Create the View

Every controller has a corresponding view. So we next need to create our PostsView.

# /web/views/posts_view.ex
defmodule Readdit.PostsView do
  use Readdit.Web, :view
end

Create the Template

The template in Phoenix is where we add our HTML. For this page we are simply going to iterate over @posts that we received from our controller and display their title and content.

<!-- /web/templates/posts/index.html.eex -->
<h1>Posts</h1>

<%= for post <- @posts do %>
  <h3><%= post.title %></h3>
  <p>
    <%= post.content %>
  </p>
<% end %>

Results

Now if we go to http://localhost:4000/posts we should see our new page and our example Post.

Next: Creating Posts