In part 1 , we created the base app, setup the database and populated it with some data. This time we move on to displaying it on your web browser.

Displaying the website

Now that we have a populated database and all the necessary ecto interfaces, it’s time to serve random images to visitors!

Routing

In the file ./lib/hi_phoenix_web/router.ex, we need to add some codes so that the right controller can be called upon a connection to your website (i.e. www.phybbit.com/img) and serve a random image.

get "/img", HiPhoenixController, :show_img

Creating the controller

Under ./lib/hi_phoenix_web/controllers, create a new file called hi_phoenix_controller.ex and copy the following code

# ./lib/hi_phoenix_web/controllers/hi_phoenix_controller.ex
defmodule HiPhoenixWeb.HiPhoenixController do
  use HiPhoenixWeb, :controller
  alias HiPhoenix.Categories

  def show_img(conn) do
    img_params = HiPhoenix.serve_img
    conn 
    |> put_layout(false)
    |> assign(:img_params, img_params)
    |> render("serve_img.html")
  end
end

Creating the webpage

In order to render the page, we need a view so let’s create one under ./lib/hi_phoenix_web/views/ and name the file hi_phoenix_view.ex. Add the following lines of code to it:

# ./lib/hi_phoenix_web/views/hi_phoenix_view.ex
defmodule HiPhoenixWeb.HiPhoenixView do
  use HiPhoenixWeb, :view
end

The view is used to render a template (using the function render/3) that will be shown to visitors.
Therefore, we need to create a template as well, under ./lib/hi_phoenix_web/templates/hi_phoenix.
In the controller, the line |> render("serve_img.html") will look for a file named serve_img.html.eex under the hi_phoenix sub-folder, so let’s create a file with the same name.

# ./lib/hi_phoenix_web/template/serve_img.html.eex
<a href=<%= @img_params[:click_url] %> target="_parent">
  <img src=<%= @img_params[:img_url] %> />
</a>

This will create the the most basic page with just 1 image that redirects the users when clicked.

Running our website

Now we have the bare minimum needed to show a webpage that serves a random clickable image every time the page is loaded.
To see it for yourself, run mix phx.server and head to http://0.0.0.0:4000/img.
You should see one of two images being displayed everytime you reload the page (or more depending on how much data you inserted using the seeds.exs file!)

That is all for part 2! In the next part we will take a look at how to build a release and deploy your application (using Distillery).
Please look forward to it!